i had configure service and respository but i till get Exception when run
My exception
An exception occurred during processing of a background job.
Autofac.Core.DependencyResolutionException
An exception was thrown while activating OBBE.Job.Server.Process.JobBillReconcile -> OBBE.Core.Services.Bill.BillService -> OBBE.Infrastructure.Integration.BillProxy.BillProxyRepository`1[[OBBE.Core.Services.Bill.BillService, OBBE.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].
Autofac.Core.DependencyResolutionException: An exception was thrown while activating OBBE.Job.Server.Process.JobBillReconcile -> OBBE.Core.Services.Bill.BillService -> OBBE.Infrastructure.Integration.BillProxy.BillProxyRepository`1[[OBBE.Core.Services.Bill.BillService, OBBE.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].
---> Autofac.Core.DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'OBBE.Infrastructure.Integration.BillProxy.BillProxyRepository`1[OBBE.Core.Services.Bill.BillService]' can be invoked with the available services and parameters:
Cannot resolve parameter 'System.Net.Http.IHttpClientFactory clientFactory' of constructor 'Void .ctor(Microsoft.Extensions.Logging.ILogger`1[OBBE.Infrastructure.Integration.BillProxy.BillProxyRepository`1[OBBE.Core.Services.Bill.BillService]], Microsoft.Extensions.Options.IOptions`1[OBBE.Job.Server.Configs.BillReconcileConfigs], System.Net.Http.IHttpClientFactory)'.
at Autofac.Core.Activators.Reflection.ReflectionActivator.<>c__DisplayClass12_0.<UseSingleConstructorActivation>b__0(ResolveRequestContext ctxt, Action`1 next)
at Autofac.Core.Resolving.Middleware.DisposalTrackingMiddleware.Execute(ResolveRequestContext context, Action`1 next)
at Autofac.Core.Resolving.Middleware.ActivatorErrorHandlingMiddleware.Execute(ResolveRequestContext context, Action`1 next)
--- End of inner exception stack trace ---
at Autofac.Core.Resolving.Middleware.ActivatorErrorHandlingMiddleware.Execute(ResolveRequestContext context, Action`1 next)
at Autofac.Core.Resolving.Middleware.SharingMiddleware.Execute(ResolveRequestContext context, Action`1 next)
at Autofac.Core.Resolving.Middleware.CircularDependencyDetectorMiddleware.Execute(ResolveRequestContext context, Action`1 next)
at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, ResolveRequest request)
at Autofac.Core.Resolving.ResolveOperation.ExecuteOperation(ResolveRequest request)
at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance)
at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable`1 parameters)
at Hangfire.AspNetCore.AspNetCoreJobActivatorScope.Resolve(Type type)
at Hangfire.Server.CoreBackgroundJobPerformer.Perform(PerformContext context)
at Hangfire.Server.BackgroundJobPerformer.<>c__DisplayClass9_0.<PerformJobWithFilters>b__0()
at Hangfire.Server.BackgroundJobPerformer.InvokePerformFilter(IServerFilter filter, PerformingContext preContext, Func`1 continuation)
at Hangfire.Server.BackgroundJobPerformer.PerformJobWithFilters(PerformContext context, IEnumerable`1 filters)
at Hangfire.Server.BackgroundJobPerformer.Perform(PerformContext context)
at Hangfire.Server.Worker.PerformJob(BackgroundProcessContext context, IStorageConnection connection, String jobId)
My service
public class BillService : IBillService
{
private readonly IBillProxyRepository<BillService> _billProxyRepository;//visual notify null here
public BillService(IBillProxyRepository<BillService> billProxyRepository)
{
billProxyRepository = _billProxyRepository;
}
public async Task<ProcessResult<BillPaymentResponse>> BillPayment(BillPaymentRequest billingRequest)
{
return await _billProxyRepository.BillPayment(billingRequest);
throw new NotImplementedException();
}
public async Task<ProcessResult<PmtStatusInqResponse>> BillStatusInq(PmtStatusInqRequest billingRequest)
{
return await _billProxyRepository.BillStatusInq(billingRequest);
throw new NotImplementedException();
}
}
My repository
public class BillProxyRepository<T> : IBillProxyRepository<T>
{
private readonly ILogger<BillProxyRepository<T>> _logger;
private readonly IOptions<BillReconcileConfigs> _config;
private readonly IHttpClientFactory _clientFactory;
public BillProxyRepository(ILogger<BillProxyRepository<T>> logger, IOptions<BillReconcileConfigs> config, IHttpClientFactory clientFactory)
{
_logger = logger;
_config = config;
_clientFactory = clientFactory;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}
my config
public class DefaultCoreModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<InformationService>()
.As<IAccountInformationService>().InstancePerLifetimeScope();
builder.RegisterType<BillService>()
.As<IBillService>().InstancePerLifetimeScope();
builder.RegisterType<AuthorizeService>()
.As<IAuthorizeService>().InstancePerLifetimeScope();
}
}
and
public class DefaultInfrastructureModule : Module
{
private readonly bool _isDevelopment = false;
private readonly List _assemblies = new List();
public DefaultInfrastructureModule(bool isDevelopment, Assembly? callingAssembly = null)
{
_isDevelopment = isDevelopment;
}
protected override void Load(ContainerBuilder builder)
{
RegisterCommonDependencies(builder);
}
private void RegisterCommonDependencies(ContainerBuilder builder)
{
// BillProxy
builder.RegisterGeneric(typeof(BillProxyRepository<>))
.As(typeof(IBillProxyRepository<>))
.InstancePerLifetimeScope();
builder.Register<ServiceFactory>(context =>
{
var c = context.Resolve<IComponentContext>();
return t => c.Resolve(t);
});
var mediatrOpenTypes = new[]
{
typeof(IRequestHandler<,>),
typeof(IRequestExceptionHandler<,,>),
typeof(IRequestExceptionAction<,>),
typeof(INotificationHandler<>),
};
foreach (var mediatrOpenType in mediatrOpenTypes)
{
builder
.RegisterAssemblyTypes(_assemblies.ToArray())
.AsClosedTypesOf(mediatrOpenType)
.AsImplementedInterfaces();
}
builder.RegisterType<EmailSender>().As<IEmailSender>()
.InstancePerLifetimeScope();
}
}
i tried but cannot, pls help me why
private readonly IBillProxyRepository _billProxyRepository;//visual notify null here
and why exception when run
Related
I am trying to send user to database using identity and sqlite, I am using swagger to contact api. When I click execute my request but I get the following error:
System.TypeInitializationException: The type initializer for 'Microsoft.EntityFrameworkCore.Query.QueryableMethods' threw an exception.
System.InvalidOperationException: Sequence contains more than one matching element
at System.Linq.ThrowHelper.ThrowMoreThanOneMatchException()
at System.Linq.Enumerable.TryGetSingle[TSource](IEnumerable1 source, Func2 predicate, Boolean& found)
at System.Linq.Enumerable.Single[TSource](IEnumerable1 source, Func2 predicate)
at Microsoft.EntityFrameworkCore.Query.QueryableMethods..cctor()
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Query.QueryableMethods.get_FirstOrDefaultWithPredicate()
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.FirstOrDefaultAsync[TSource](IQueryable1 source, Expression1 predicate, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore6.FindByNameAsync(String normalizedUserName, CancellationToken cancellationToken) at Microsoft.AspNetCore.Identity.UserManager1.FindByNameAsync(String userName)
at Microsoft.AspNetCore.Identity.UserValidator1.ValidateUserName(UserManager1 manager, TUser user, ICollection1 errors) at Microsoft.AspNetCore.Identity.UserValidator1.ValidateAsync(UserManager1 manager, TUser user) at Microsoft.AspNetCore.Identity.UserManager1.ValidateUserAsync(TUser user)
at Microsoft.AspNetCore.Identity.UserManager`1.CreateAsync(TUser user)
at DateApp.Controllers.HomeController.Register() in /Users/michal/Projects/DateApp/DateApp/Controllers/HomeController.cs:line 78
I am expecting to push new user to my sqlite database.
My code - controller:
[HttpPost("add")]
public async Task<IActionResult> Register()
{
if (ModelState.IsValid)
{
var user = new IdentityUser
{
UserName = "admin",
Email = "aadmin#gmail.com"
};
//create without password
var res = await _userManager.CreateAsync(user);
if (!res.Succeeded)
{
var exceptionText = res.Errors.Aggregate("User Creation Failed - Identity Exception. Errors were: \n\r\n\r", (current, error) => current + (" - " + error + "\n\r"));
throw new Exception(exceptionText);
}
}
return Ok();
}
DbContext:
using System;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using DateApp.Models;
namespace DateApp.Db
{
public class AppDBContext : IdentityDbContext
{
private readonly DbContextOptions _options;
public AppDBContext(DbContextOptions options) : base(options)
{
_options = options;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
}
I am getting below exception for Web Api App Service:
Category: Microsoft.AspNetCore.Server.IIS.Core.IISHttpServer EventId: 2 RequestId: 8000001b-0000-6000-b63f-84710c7967bb
RequestPath: /api/notification/RetrieveNotifications SpanId:
93ff3a8b0da39d4f TraceId: 730bf862b1072a409c402c3b795488ad ParentId:
251526087660f84b Connection ID "6917529029251694618", Request ID
"8000001b-0000-6000-b63f-84710c7967bb": An unhandled exception was
thrown by the application. Exception:
Microsoft.Azure.Cosmos.CosmosException : Response status code does not
indicate success: InternalServerError (500); Substatus: 0; ActivityId:
00000000-0000-0000-0000-000000000000; Reason: (Cannot access a
disposed object. Object name: 'Accessing CosmosClient after it is
disposed is invalid.'.); ---> System.ObjectDisposedException: Cannot
access a disposed object. Object name: 'Accessing CosmosClient after
it is disposed is invalid.'. at
Microsoft.Azure.Cosmos.ClientContextCore.ThrowIfDisposed() at
Microsoft.Azure.Cosmos.ClientContextCore.ThrowIfDisposed[T](T input)
at Microsoft.Azure.Cosmos.ClientContextCore.get_DocumentClient() at
Microsoft.Azure.Cosmos.CosmosClient.get_DocumentClient() at
Microsoft.Azure.Cosmos.Handlers.TransportHandler.ProcessMessageAsync(RequestMessage
request, CancellationToken cancellationToken) at
Microsoft.Azure.Cosmos.Handlers.TransportHandler.SendAsync(RequestMessage
request, CancellationToken cancellationToken) at
Microsoft.Azure.Cosmos.RequestHandler.SendAsync(RequestMessage
request, CancellationToken cancellationToken) at
Microsoft.Azure.Cosmos.Handlers.AbstractRetryHandler.ExecuteHttpRequestAsync(Func`2
callbackMethod, Func`4 callShouldRetry, Func`4
callShouldRetryException, ITrace trace, CancellationToken
cancellationToken) at
Microsoft.Azure.Cosmos.Handlers.AbstractRetryHandler.SendAsync(RequestMessage
request, CancellationToken cancellationToken) at
Microsoft.Azure.Cosmos.RequestHandler.SendAsync(RequestMessage
request, CancellationToken cancellationToken) at
Microsoft.Azure.Cosmos.RequestHandler.SendAsync(RequestMessage
request, CancellationToken cancellationToken) at
Microsoft.Azure.Cosmos.Handlers.RequestInvokerHandler.SendAsync(RequestMessage
request, CancellationToken cancellationToken) at
Microsoft.Azure.Cosmos.Handlers.RequestInvokerHandler.SendAsync(String
resourceUriString, ResourceType resourceType, OperationType
operationType, RequestOptions requestOptions, ContainerInternal
cosmosContainerCore, FeedRange feedRange, Stream streamPayload,
Action`1 requestEnricher, ITrace trace, CancellationToken
cancellationToken) at
Microsoft.Azure.Cosmos.CosmosQueryClientCore.ExecuteItemQueryAsync(String
resourceUri, ResourceType resourceType, OperationType operationType,
Guid clientQueryCorrelationId, FeedRange feedRange,
QueryRequestOptions requestOptions, SqlQuerySpec sqlQuerySpec, String
continuationToken, Boolean isContinuationExpected, Int32 pageSize,
ITrace trace, CancellationToken cancellationToken) at
Microsoft.Azure.Cosmos.Pagination.NetworkAttachedDocumentContainer.MonadicQueryAsync(SqlQuerySpec
sqlQuerySpec, FeedRangeState`1 feedRangeState, QueryPaginationOptions
queryPaginationOptions, ITrace trace, CancellationToken
cancellationToken) at
Microsoft.Azure.Cosmos.Pagination.PartitionRangePageAsyncEnumerator`2.MoveNextAsync(ITrace
trace) at
Microsoft.Azure.Cosmos.Pagination.BufferedPartitionRangePageAsyncEnumerator`2.PrefetchAsync(ITrace
trace, CancellationToken cancellationToken) at
Microsoft.Azure.Cosmos.Pagination.BufferedPartitionRangePageAsyncEnumerator`2.GetNextPageAsync(ITrace
trace, CancellationToken cancellationToken) at
Microsoft.Azure.Cosmos.Pagination.PartitionRangePageAsyncEnumerator`2.MoveNextAsync(ITrace
trace) at
Microsoft.Azure.Cosmos.Pagination.CrossPartitionRangePageAsyncEnumerator`2.MoveNextAsync(ITrace
trace) at
Microsoft.Azure.Cosmos.Query.Core.Pipeline.CrossPartition.Parallel.ParallelCrossPartitionQueryPipelineStage.MoveNextAsync(ITrace
trace) at
Microsoft.Azure.Cosmos.Query.Core.Pipeline.LazyQueryPipelineStage.MoveNextAsync(ITrace
trace) at
Microsoft.Azure.Cosmos.Query.Core.Pipeline.NameCacheStaleRetryQueryPipelineStage.MoveNextAsync(ITrace
trace) at
Microsoft.Azure.Cosmos.Query.Core.Pipeline.CatchAllQueryPipelineStage.MoveNextAsync(ITrace
trace) --- End of inner exception stack trace --- at
Microsoft.Azure.Cosmos.ClientContextCore.ThrowIfDisposed() at
Microsoft.Azure.Cosmos.ClientContextCore.ThrowIfDisposed[T](T input)
at Microsoft.Azure.Cosmos.ClientContextCore.get_DocumentClient() at
Microsoft.Azure.Cosmos.CosmosClient.get_DocumentClient() at
Microsoft.Azure.Cosmos.Handlers.TransportHandler.ProcessMessageAsync(RequestMessage
request, CancellationToken cancellationToken) at
Microsoft.Azure.Cosmos.Handlers.TransportHandler.SendAsync(RequestMessage
request, CancellationToken cancellationToken) at
Microsoft.Azure.Cosmos.RequestHandler.SendAsync(RequestMessage
request, CancellationToken cancellationToken) at
Microsoft.Azure.Cosmos.Handlers.AbstractRetryHandler.ExecuteHttpRequestAsync(Func`2
callbackMethod, Func`4 callShouldRetry, Func`4
callShouldRetryException, ITrace trace, CancellationToken
cancellationToken) at
Microsoft.Azure.Cosmos.Handlers.AbstractRetryHandler.SendAsync(RequestMessage
request, CancellationToken cancellationToken) at
Microsoft.Azure.Cosmos.RequestHandler.SendAsync(RequestMessage
request, CancellationToken cancellationToken) at
Microsoft.Azure.Cosmos.RequestHandler.SendAsync(RequestMessage
request, CancellationToken cancellationToken) at
Microsoft.Azure.Cosmos.Handlers.RequestInvokerHandler.SendAsync(RequestMessage
request, CancellationToken cancellationToken) at
Microsoft.Azure.Cosmos.Handlers.RequestInvokerHandler.SendAsync(String
resourceUriString, ResourceType resourceType, OperationType
operationType, RequestOptions requestOptions, ContainerInternal
cosmosContainerCore, FeedRange feedRange, Stream streamPayload,
Action`1 requestEnricher, ITrace trace, CancellationToken
cancellationToken) at
Microsoft.Azure.Cosmos.CosmosQueryClientCore.ExecuteItemQueryAsync(String
resourceUri, ResourceType resourceType, OperationType operationType,
Guid clientQueryCorrelationId, FeedRange feedRange,
QueryRequestOptions requestOptions, SqlQuerySpec sqlQuerySpec, String
continuationToken, Boolean isContinuationExpected, Int32 pageSize,
ITrace trace, CancellationToken cancellationToken) at
Microsoft.Azure.Cosmos.Pagination.NetworkAttachedDocumentContainer.MonadicQueryAsync(SqlQuerySpec
sqlQuerySpec, FeedRangeState`1 feedRangeState, QueryPaginationOptions
queryPaginationOptions, ITrace trace, CancellationToken
cancellationToken) at
Microsoft.Azure.Cosmos.Pagination.PartitionRangePageAsyncEnumerator`2.MoveNextAsync(ITrace
trace) at
Microsoft.Azure.Cosmos.Pagination.BufferedPartitionRangePageAsyncEnumerator`2.PrefetchAsync(ITrace
trace, CancellationToken cancellationToken) at
Microsoft.Azure.Cosmos.Pagination.BufferedPartitionRangePageAsyncEnumerator`2.GetNextPageAsync(ITrace
trace, CancellationToken cancellationToken) at
Microsoft.Azure.Cosmos.Pagination.PartitionRangePageAsyncEnumerator`2.MoveNextAsync(ITrace
trace) at
Microsoft.Azure.Cosmos.Pagination.CrossPartitionRangePageAsyncEnumerator`2.MoveNextAsync(ITrace
trace) at
Microsoft.Azure.Cosmos.Query.Core.Pipeline.CrossPartition.Parallel.ParallelCrossPartitionQueryPipelineStage.MoveNextAsync(ITrace
trace) at
Microsoft.Azure.Cosmos.Query.Core.Pipeline.LazyQueryPipelineStage.MoveNextAsync(ITrace
trace) at
Microsoft.Azure.Cosmos.Query.Core.Pipeline.NameCacheStaleRetryQueryPipelineStage.MoveNextAsync(ITrace
trace) at
Microsoft.Azure.Cosmos.Query.Core.Pipeline.CatchAllQueryPipelineStage.MoveNextAsync(ITrace
trace) --- Cosmos Diagnostics
---{"name":"NoOp","id":"00000000-0000-0000-0000-000000000000","component":"Unknown","caller
info":{"member":"NoOp","file":"NoOp","line":9001},"start
time":"12:00:00:000","duration in
milliseconds":0,"data":{},"children":[]}
I am using Cosmos DB and creating the instance in the startup.cs
public class Startup
{
private const string CosmosDBEndpoint = "CosmosDBEndpoint";
private const string CosmosDBAuthKey = "CosmosDBAuthKey";
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
RegisterCosmosClient(services, Configuration);
services.AddTransient(typeof(ICosmosDbRepository<>), typeof(CosmosDbRepository<>));
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Shell Fleet Hub Notifications WebApi", Version = "v1", });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
endpoints.MapControllers();
});
app.UseSwagger();
}
private static void RegisterCosmosClient(IServiceCollection serviceCollection, IConfiguration configuration)
{
string cosmosDbEndpoint = configuration[CosmosDBEndpoint];
string cosmosDbAuthKey = configuration[CosmosDBAuthKey];
serviceCollection.AddSingleton(s => new CosmosClient(cosmosDbEndpoint, cosmosDbAuthKey,
new CosmosClientOptions { AllowBulkExecution = true }));
}
}
Cosmos DB Repository:
public class CosmosDbRepository<T> : ICosmosDbRepository<T> where T : class
{
public static readonly string CollectionId = GetAttributeCosmoDbCollection<T>(typeof(T));
private readonly CosmosClient _client;
private Container _container;
private Database _database;
private const string CosmosDbId = "CosmosDbId";
private readonly IGetConfigurationSettings _configurationSettings;
public CosmosDbRepository(CosmosClient client, IGetConfigurationSettings configurationSettings)
{
_client = client;
_configurationSettings = configurationSettings;
Task.Run(async () =>
{
await CreateDatabaseIfNotExistsAsync();
await CreateContainerIfNotExistsAsync();
}).Wait();
}
public async Task<ItemResponse<T>> CreateItemAsync(T item, string partitionKeyValue)
{
return await _container.CreateItemAsync<T>(item, new PartitionKey(partitionKeyValue));
}
public async Task<IEnumerable<T>> GetItemsAsync(string queryString)
{
var query = _container.GetItemQueryIterator<T>(new QueryDefinition(queryString));
List<T> results = new List<T>();
while (query.HasMoreResults)
{
var response = await query.ReadNextAsync();
results.AddRange(response.ToList());
}
return results;
}
public async Task<IEnumerable<T>> GetItemsAsync(Expression<Func<T, bool>> predicate, Expression<Func<T, object>> orderByDesc, int takeCount = -1)
{
var criteria = _container.GetItemLinqQueryable<T>(true,
continuationToken: null,
new QueryRequestOptions { MaxItemCount = takeCount })
.Where(predicate)
.OrderByDescending(orderByDesc)
.ToFeedIterator();
var query = criteria;
var results = new List<T>();
while (query.HasMoreResults)
{
if (takeCount > -1 && results.Count >= takeCount) break;
results.AddRange(await query.ReadNextAsync());
}
return results;
}
public async Task<IEnumerable<T>> GetItemsAsync(Expression<Func<T, bool>> predicate, Expression<Func<T, object>> orderByDesc, string partitionKey, int takeCount = -1)
{
var criteria = _container.GetItemLinqQueryable<T>(allowSynchronousQueryExecution: false,
continuationToken: null,
new QueryRequestOptions { PartitionKey = new PartitionKey(partitionKey) })
.Where(predicate)
.OrderByDescending(orderByDesc)
.ToFeedIterator();
var query = criteria;
var results = new List<T>();
while (query.HasMoreResults)
{
if (takeCount > -1 && results.Count >= takeCount) break;
results.AddRange(await query.ReadNextAsync());
}
return results;
}
public Task<ItemResponse<T>> UpdateItemAsync(string id, T item)
{
return _container.ReplaceItemAsync<T>(item, id);
}
private async Task CreateDatabaseIfNotExistsAsync()
{
_database = await _client
.CreateDatabaseIfNotExistsAsync(_configurationSettings.Get(CosmosDbId));
}
private async Task CreateContainerIfNotExistsAsync()
{
_container = await _database
.CreateContainerIfNotExistsAsync(new ContainerProperties(CollectionId, $"/{GetPartitionKeyAttributeCosmoDbCollection(typeof(T))}"));
}
private string GetPartitionKeyAttributeCosmoDbCollection(Type t)
{
var attribute = (CosmoDBContainerAttribute)Attribute.GetCustomAttribute(t, typeof(CosmoDBContainerAttribute));
return attribute.PartitionKey;
}
private static string GetAttributeCosmoDbCollection<T>(Type t)
{
var attribute = (CosmoDBContainerAttribute)Attribute.GetCustomAttribute(t, typeof(CosmoDBContainerAttribute));
return attribute.Name;
}
}
Below is how I am using this repository:
public class RetrieveUserSubscriptionQueryHandler : IQueryHandler<RetrieveUserSubscriptionQuery, ResultDto>
{
private readonly ICosmosDbRepository<UserSubscriptions> _userSubscriptionRepository;
public RetrieveUserSubscriptionQueryHandler(ICosmosDbRepository<UserSubscriptions> userSubscriptionRepository)
{
_userSubscriptionRepository = userSubscriptionRepository;
}
public async Task<ResultDto> HandleAsync(RetrieveUserSubscriptionQuery query, ILogger logger)
{
logger.LogInformation($"Started {nameof(RetrieveNotificationQueryHandler)} with UUID:{query.UserUUId}");
var userSubscriptions = await GetUserSubscriptions(query, logger);
return new ResultDto
{
ResultType = ResultType.Success,
Data = userSubscriptions
};
}
private async Task<UserSubscriptionDto> GetUserSubscriptions(RetrieveUserSubscriptionQuery query, ILogger logger)
{
var dto = new UserSubscriptionDto
{
UserId = query.UserUUId,
Subscriptions = new List<SubscriptionDto>(),
UiNotifications = new List<NotificationCategoryType>(),
EmailNotifications = new List<NotificationCategoryType>()
};
var userSubscriptions = await _userSubscriptionRepository
.GetItemsAsync(s => s.UUID == query.UserUUId, o => o.UUID);
if (userSubscriptions.Any())
{
logger.LogInformation($"subscriptions found for UUID:{query.UserUUId}");
foreach (var userSubscription in userSubscriptions)
{
if (userSubscription.Type.Equals(UserSubscriptionType.Subscription.ToString(), StringComparison.OrdinalIgnoreCase))
{
foreach (var item in userSubscription.Events)
{
var notificationCategory = Utility.GetNotificationCategoryType((NotificationType)item.EventType);
if (item.Channels.Any(x => x == (int)ChannelType.UI) && !dto.UiNotifications.Contains(notificationCategory))
{
dto.UiNotifications.Add(notificationCategory);
}
if (item.Channels.Any(x => x == (int)ChannelType.Email) && !dto.EmailNotifications.Contains(notificationCategory))
{
dto.EmailNotifications.Add(notificationCategory);
}
}
}
else if (userSubscription.Type.Equals(UserSubscriptionType.Accounts.ToString(), StringComparison.OrdinalIgnoreCase))
{
foreach (var payer in userSubscription.Payers)
{
dto.Subscriptions.Add(new SubscriptionDto
{
PayerNumber = payer.PayerNumber,
AccountNumbers = payer.Accounts
});
}
}
}
}
else
{
logger.LogInformation($"No subscriptions found for UUID:{query.UserUUId}");
}
return dto;
}
}
I have implemented Unit Of Work and facing following the error, earlier the project implemented well when I just implemented Repository. This is the error I'm getting in my Browser (Google Chrome Version 90.0.4430.212 (Official Build) (64-bit)):
Server Error in '/' Application.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[MissingMethodException: No parameterless constructor defined for this object.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +122
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +239
System.Activator.CreateInstance(Type type, Boolean nonPublic) +85
System.Activator.CreateInstance(Type type) +12
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +55
[InvalidOperationException: An error occurred when trying to create a controller of type 'OfficeWork.Controllers.PopulationsController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +178
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +102
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +188
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +105
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.8.4330.0
"IUnitOfWork" interface:
using System.Threading.Tasks;
namespace OfficeWork.DAL
{
interface IUnitOfWork
{
IStudentRepository StudentRepository { get; }
IStudentRepositoryRole StudentRepositoryRole { get; }
Task<bool> SaveAsync();
}
}
UnitOfWork:
using System.Threading.Tasks;
namespace OfficeWork.DAL
{
public class UnitOfWork : IUnitOfWork
{
private readonly PopulationDBContext dc;
public UnitOfWork(PopulationDBContext dc)
{
this.dc = dc;
}
public IStudentRepository StudentRepository =>
new StudentRepository(dc);
public IStudentRepositoryRole StudentRepositoryRole =>
new StudentRepositoryRole(dc);
public async Task<bool> SaveAsync()
{
return await dc.SaveChangesAsync() > 0;
}
}
}
Controller:
using OfficeWork.DAL;
using OfficeWork.ED;
using OfficeWork.Models;
using System.Collections.Generic;
using System.Web.Mvc;
namespace OfficeWork.Controllers
{
public class PopulationsController : Controller
{
private readonly IUnitOfWork uow;
Password password_hiding = new Password();
PopulationsController(IUnitOfWork uow)
{
this.uow = uow;
}
//Direct to homepage after logging in
public ActionResult HomePage(int id)
{
Population population = uow.StudentRepository.GetStudentByID(id);
return View(population);
}
//Controller used to update existing information
[HttpPost]
public ActionResult UpdatePopulation(Population std, int id)
{
{
Population updatestd = uow.StudentRepository.GetStudentByID(id);
if (!string.IsNullOrWhiteSpace(std.Email)) { updatestd.Email = std.Email; }
if (!string.IsNullOrWhiteSpace(std.FirstName)) { updatestd.FirstName = std.FirstName; }
if (!string.IsNullOrWhiteSpace(std.LastName)) { updatestd.LastName = std.LastName; }
{ updatestd.MobileNumber = std.MobileNumber; }
{ updatestd.DateOfBirth = std.DateOfBirth; }
{ updatestd.Password =password_hiding.encrypt(std.Password); }
uow.StudentRepository.UpdateStudent(updatestd);
uow.SaveAsync();
}
return Json(true, JsonRequestBehavior.AllowGet);
}
//Controller used to direct to the Edit page
public ActionResult Edit(int val)
{
Population p = uow.StudentRepository.GetStudentByID(val);
p.Password = password_hiding.Decrypt(p.Password);
return View(p);
}
//Main page is the page consisting of user details
public ActionResult UserDetails(int val)
{
Population std = uow.StudentRepository.GetStudentByID(val);
return View(std);
}
public ActionResult SignIn(int? id)
{
return View();
}
//This post Sign in controller helps in authenticating user and redirecting it the user details page
[HttpPost]
public ActionResult SignIn(string email, string password)
{
var new_pas =password_hiding.encrypt(password);
Population dbs = uow.StudentRepository.GetStudentByEmailPass(email, new_pas);
int id = dbs.ID;
Role ro = uow.StudentRepositoryRole.GetStudentByID(id);
if(ro!=null)
{
return RedirectToAction("Admin");
}
if (dbs != null)
{
return RedirectToAction("HomePage/"+id);
}
else
{
return View();
}
}
public ActionResult SignUp()
{
return View();
}
// This POST controller is used to sign up. It takes values(Email,FirstName,LastName,MobileNumber,DateOfBirth,Password) from the page and add it to the database.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SignUp([Bind(Include = "Email,FirstName,LastName,MobileNumber,DateOfBirth,Password")] Population population)
{
if (ModelState.IsValid)
{
population.Password =password_hiding.encrypt(population.Password);
uow.StudentRepository.InsertStudent(population);
uow.SaveAsync();
return RedirectToAction("SignIn");
}
return View(population);
}
//If Username: anirudhrawat1#gmail.com and Password:Solution or Username: arnav#gmail.com and Password: Hello is entered to SIGN IN page then it will direct the user to List of entries.
public ActionResult Admin()
{
IEnumerable<Population> students = uow.StudentRepository.GetStudents();
return View(students);
}
}
}
"StudentRepository" repository file of "Population":
using OfficeWork.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
namespace OfficeWork.DAL
{
public class StudentRepository : IStudentRepository, IDisposable
{
private PopulationDBContext context;
public StudentRepository(PopulationDBContext context)
{
this.context = context;
}
public IEnumerable<Population> GetStudents()
{
return context.Populations.ToList();
}
public Population GetStudentByID(int id)
{
return context.Populations.Find(id);
}
public Population GetStudentByEmailPass(string email, string password)
{
return context.Populations.FirstOrDefault(e => e.Email == email && e.Password == password);
}
public void InsertStudent(Population student)
{
context.Populations.Add(student);
}
public void DeleteStudent(int studentID)
{
Population student = context.Populations.Find(studentID);
context.Populations.Remove(student);
}
public void UpdateStudent(Population student)
{
context.Entry(student).State = EntityState.Modified;
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
"IStudentRepository" interface file:
using OfficeWork.Models;
using System;
using System.Collections.Generic;
namespace OfficeWork.DAL
{
public interface IStudentRepository : IDisposable
{
IEnumerable<Population> GetStudents();
Population GetStudentByID(int studentId);
void InsertStudent(Population student);
Population GetStudentByEmailPass(string email, string password);
void DeleteStudent(int studentID);
void UpdateStudent(Population student);
}
}
"StudentRepositoryRole" repository file of "Role":
using OfficeWork.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
namespace OfficeWork.DAL
{
public class StudentRepositoryRole : IStudentRepositoryRole, IDisposable
{
private PopulationDBContext context;
public StudentRepositoryRole(PopulationDBContext context)
{
this.context = context;
}
public IEnumerable<Role> GetStudents()
{
return context.Roles.ToList();
}
public Role GetStudentByID(int id)
{
return context.Roles.Find(id);
}
public void InsertStudent(Role student)
{
context.Roles.Add(student);
}
public void DeleteStudent(int studentID)
{
Role student = context.Roles.Find(studentID);
context.Roles.Remove(student);
}
public void UpdateStudent(Role student)
{
context.Entry(student).State = EntityState.Modified;
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
"IstudentRepositoryRole" interface file:
using OfficeWork.Models;
using System;
using System.Collections.Generic;
namespace OfficeWork.DAL
{
public interface IStudentRepositoryRole : IDisposable
{
IEnumerable<Role> GetStudents();
Role GetStudentByID(int studentId);
void InsertStudent(Role student);
void DeleteStudent(int studentID);
void UpdateStudent(Role student);
}
}
PopulationDBContext:
using OfficeWork.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace OfficeWork.DAL
{
public class PopulationDBContext : DbContext
{
public DbSet<Population> Populations { get; set; }
public DbSet<Role> Roles { get; set; }
}
}
The main issue was "dependency injection".
private readonly IUnitOfWork uow;
PopulationsController(IUnitOfWork uow)
{
this.uow = uow;
}
I installed Unity.Mvc5 from Nuget Packages. I has in-built configuration to make dependency injections.
After adding Unity.Mvc5. It created UnityConfig.cs file in App_start automatically.
1)Add "container.RegisterType<Interface, Repository>();" in UnityConfig.cs
2)Add "UnityConfig.RegisterComponents();" in Global.asax.cs.
Im a little bit confused about UserManager.Create(...).
When I use the Standard EntityFramework's IdentityUser to create and add a new User everything works fine. EntityFramework creates a database if none exists with my connectionstring Data Source=(LocalDb)\MSSQLLocalDB;Database=IdentityDemo;trusted_connection=yes; and adds a User to the Database.
ExampleProgram:
static void Main(string[] args)
{
var username = "ygg";
var password = "Password123!";
var userStore = new UserStore<IdentityUser>();
var userManager = new UserManager<IdentityUser>(userStore);
var creationResult = userManager.Create(new IdentityUser(username), password);
}
But when i try to use my own CustomUser, EntityFramework does nothing and i get a NullReferenceException at UserManager.Create(...).
Here is my Extended CustomUser Project:
static void Main(string[] args)
{
var userName = "Ygg";
var password = "Password123!";
var userStore = new CustomUserStore(new CustomUserDbContext());
var userManager = new UserManager<CustomUser, int>(userStore);
var creationResult = userManager.Create(
new CustomUser {UserName = userName}, password); //<--- Exception Here
}
CustomUser-class:
public class CustomUser : IUser<int>
{
public int Id { get; set; }
public string UserName { get; set; }
public string PasswordHash { get; set; }
}
CustomUserDbContext:
public class CustomUserDbContext : IdentityDbContext
{
public CustomUserDbContext() : base("DefaultConnection")
{
}
public DbSet<CustomUser> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var user = modelBuilder.Entity<CustomUser>();
user.ToTable("Users");
user.HasKey(x => x.Id);
user.Property(x => x.Id).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
user.Property(x => x.UserName).IsRequired().HasMaxLength(256)
.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("UserNameIndex") { IsUnique = true }));
base.OnModelCreating(modelBuilder);
}
}
And last but not least, CustomUserStore:
public class CustomUserStore : IUserPasswordStore<CustomUser, int>
{
private readonly CustomUserDbContext _context;
public CustomUserStore(CustomUserDbContext context)
{
_context = context;
}
public void Dispose()
{
_context.Dispose();
}
public Task CreateAsync(CustomUser user)
{
_context.Users.Add(user);
return _context.SaveChangesAsync();
}
.
.
.
}
Exception:
object reference not set to an instance of an object
Stacktrace:
bei Microsoft.AspNet.Identity.UserManager2.<UpdatePassword>d__39.MoveNext()
bei System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
bei Microsoft.AspNet.Identity.UserManager2.d__d.MoveNext()
bei System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
bei Microsoft.AspNet.Identity.AsyncHelper.RunSync[TResult](Func1 func)
bei Microsoft.AspNet.Identity.UserManagerExtensions.Create[TUser,TKey](UserManager2 manager, TUser user, String password)
bei Identity.Program.Main(String[] args) in E:\syncplicity\z003apfp\Documents\Visual Studio 2015\Projects\Identity\Identity\Program.cs:Zeile 21.
bei System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
bei System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
I'm using EntityFramework 6.1.0 and AspNet.Identity.Core 2.2.1
Did i miss anything to configure, so AspNet.Identity and EntityFrameworks accepts my own implementations here?
Any help or thoughts where the problem lies, is appreciated.
I already tried to create the database first and then try to add a User using userManager.Create(new CustomUser {UserName = userName}, password), but this leads also to the same NullReferenceException
When you override something you should do it for the whole structure of Identity.
For example your DB Context should use something like this:
Custom Context
CustomUserDbContext : IdentityDbContext<CustomUser, CustomRole, int, CustomUserLogin, CustomUserRole, CustomUserClaim>
Custom User
User : IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>
Custom Role
CustomRole : IdentityRole<int, CustomUserRole> { }
Custom UserLogin
public class CustomUserLogin : IdentityUserLogin<int> { }
CustomUserClaim
public class CustomUserClaim : IdentityUserClaim<int> { }
Note that was an example yous should adapt according to your need.
I have a asp.net webform which writes about 25-30 items(has info required when user makes follow up request from the form) into a custom cache. Currently all this happens synchronously on the main thread. But at higher loads addcache is becoming a bottleneck.
How can i run this task in the background without consuming threads from the asp.net worker process thread pool.
Alternatives:
Completely async:
Call the server code using AJAX from the client, and add code to monitor the process of the call
I just added an answer related to this process:
https://stackoverflow.com/a/11524718/1268570
Partially async:
The call from the client to the server will be sync which means the response won't be returned to the client until the whole process ends, but the real code will be executed async releasing the thread used by ASP.Net increasing scalability
Execute the page async. You need to implement the IHttpAsyncHandler interface in your ASPX code behind. This is an example:
public partial class _Default : System.Web.UI.Page, IHttpAsyncHandler
{
public void EndProcessRequest(IAsyncResult result)
{
var context = (result as AsyncOperation).Context;
context.Response.Write(string.Format("<p>End Process Request on {0}</p>", Thread.CurrentThread.ManagedThreadId.ToString()));
}
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
var operation = new AsyncOperation(cb, this.Context, extraData);
operation.StartAsync();
this.Context.Response.Write(string.Format("<p>Begin Process Request on: {0}...</p>", Thread.CurrentThread.ManagedThreadId.ToString()));
return operation;
}
}
public class AsyncOperation : IAsyncResult
{
private AsyncCallback asyncCallback;
public AsyncOperation(AsyncCallback asyncCallback, HttpContext context, object state)
{
this.AsyncState = state;
this.asyncCallback = asyncCallback;
this.Context = context;
this.IsCompleted = false;
this.AsyncWaitHandle = null;
this.CompletedSynchronously = false;
}
public HttpContext Context { get; private set; }
public object AsyncState { get; private set; }
public WaitHandle AsyncWaitHandle { get; private set; }
public bool CompletedSynchronously { get; private set; }
public bool IsCompleted { get; private set; }
public void StartAsync()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(StartAsyncOperation), this.AsyncState);
}
public void StartAsyncOperation(object workItemState)
{
// place here the async logic
this.Context.Response.Write(string.Format("<p>Long Async operation started on: {0}</p>", Thread.CurrentThread.ManagedThreadId.ToString()));
Thread.Sleep(2000);
this.Context.Response.Write(string.Format("<p>Long Async operation ended on: {0}</p>", Thread.CurrentThread.ManagedThreadId.ToString()));
this.IsCompleted = true;
this.asyncCallback(this);
}
}
Output
Create an HttpAsyncHandler. You need to create a custom HttpHandler implementing the IHttpAsyncHandler interface. Example:
public class AsyncHandler : IHttpAsyncHandler
{
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
var operation = new AsyncOperation(cb, context, extraData);
operation.StartAsync();
context.Response.Write(string.Format("<p>Begin Process Request on: {0}...</p>", Thread.CurrentThread.ManagedThreadId.ToString()));
return operation;
}
public void EndProcessRequest(IAsyncResult result)
{
var context = (result as AsyncOperation).Context;
context.Response.Write(string.Format("<p>End Process Request on {0}</p>", Thread.CurrentThread.ManagedThreadId.ToString()));
}
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
throw new NotImplementedException();
}
}