Unable to resolve service for type 'Domain.IBlobModelCache' while attempting to activate 'Domain.EntityMaterializerSource' - asp.net-core

Although the error message seems obvious I believe it is different from other questions. As you can see in my Startup I have registered IBlobModelCache service.
public class Startup
{
...
public virtual void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<DataContext>(options =>
{
options
.ReplaceService<IEntityMaterializerSource, Domain.EntityMaterializerSource>();
.UseSqlServer(
Configuration.GetConnectionString("Default"),
opt => opt.MigrationsAssembly("API")
);
});
services
.AddAuthentication(ConfigureAthentication)
.AddJwtBearer(ConfigureJwtBearer);
services
.AddLogging(ConfigureLogging)
.AddTransient<IBlobPersisterFactory, BlobPersisterFactory>()
.AddTransient<IBlobDbContextSavingHandler, BlobDbContextSavingHandler>()
.AddTransient<IBlobDbContextModelCreator, BlobDbContextModelCreator>()
.AddSingleton<IBlobModelCache, BlobModelCache>() // It is here
.AddOptions<DiskBlobStorageSettings>().Configure<IConfiguration>((settings, config) => config.Bind("BlobStorage", settings));
}
...
}
And here the constructor of my services so you can see that there is not any loop in them.
class EntityMaterializerSource : Base.EntityMaterializerSource
{
public EntityMaterializerSource(
[NotNull] EntityMaterializerSourceDependencies dependencies,
IBlobModelCache blobModelCache
)
: base(dependencies)
{
BlobModelCache = blobModelCache;
OnMaterializedMethod = typeof(EntityMaterializerSource)
.GetMethod(nameof(OnMaterialized), BindingFlags.Instance | BindingFlags.NonPublic);
}
}
class BlobModelCache : IBlobModelCache
{
// Has no constructor
}
The BlobModelCache is resolved in other services successfully and the error only happens when EF needs to materialize entities.
All I need is to be notified when an entity is materialized from DB and I could not find any solution but extending EntityMaterializerSource. I am using EF Core 3.1.8 and ASP.Net Core 3.1.

Related

Error accessing a service that uses DbContext on my quartz job

I am making a web API using ASP.NET Core and now I am having a problem with quartz scheduled jobs. The jobs I have will access my services to update the database. After some researches, I figured how to do the dependency injection so that my jobs can access the services, here is how I overrode the job factory:
public class AspNetCoreJobFactory : SimpleJobFactory
{
IServiceProvider _provider;
public AspNetCoreJobFactory(IServiceProvider provider)
{
_provider = provider;
}
public override IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
try
{
return (IJob)this._provider.GetService(bundle.JobDetail.JobType);
}
catch(Exception e)
{
throw new SchedulerException(string.Format("Problem while instantiating job '{0}' from the AspNet Core IOC.", bundle.JobDetail.Key), e);
}
}
}
and I added this line on my startup configure:
_quartzScheduler.JobFactory = new AspNetCoreJobFactory(app.ApplicationServices);
Lastly I added those two lines on my ConfigureServices method:
services.AddSingleton<IUserService, UserService>();
services.AddTransient<BatchJobCheckContract>();
right now I am getting this exception when trying to execute the job, it seems like it's because my service uses the DbContext, how can I solve this?
Cannot consume scoped service 'RHP.data.RHPDbContext' from singleton
'RHP.data.IServices.Administration.IUserService'.
After playing around with Quartz (version 3.2.3), it looks like you do not have to write your own JobFactory to use Microsoft DI. (See ASP.NET Core Integration and Microsoft DI Integration):
Add the Quartz.AspNetCore nuget package and you can scoped services like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IScopedService, ScopedService>();
// Job has scoped dependencies, so it must be scoped as well
services.AddScoped<Job>();
services.AddQuartz(q =>
{
q.UseMicrosoftDependencyInjectionScopedJobFactory();
var jobKey = new JobKey("job");
q.AddJob<Job>(jobKey);
q.AddTrigger(t => /* ... */));
});
services.AddQuartzServer(opts => opts.WaitForJobsToComplete = true);
}
However, if you cannot use the current version of Quartz.AspNetCore, you could still
use IServiceProvider as dependency in your Job class and resolve services there:
public class Job : IJob
{
private readonly IServiceProvider _serviceProvider;
public Job(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public Task Execute(IJobExecutionContext context)
{
using var scope = _serviceProvider.CreateScope();
var scopedService = scope.ServiceProvider.GetRequiredService<IScopedService>();
// ...
}
}
Like this the Job class controls the lifetime of scoped services.
I've previously had a similar problem with background tasks, you might need to create a scope.
I've adapted this code and applied it to your use case.
public class AspNetCoreJobFactory : SimpleJobFactory
{
IServiceProvider _provider;
public AspNetCoreJobFactory(IServiceProvider provider)
{
_provider = provider;
}
public override IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
try
{
using(var serviceScope = _provider.CreateScope())
{
var services = serviceScope.ServiceProvider.
return (IJob)services.GetService(bundle.JobDetail.JobType);
}
}
catch(Exception e)
{
throw new SchedulerException(string.Format("Problem while instantiating job '{0}' from the AspNet Core IOC.", bundle.JobDetail.Key), e);
}
}
}

How to access Configuration within an IHostingStartup implementation?

Trying to get access to IConfiguration from within an IHostingStartup implementation and constructor injection is not supported.
The normal Startup.cs implementation allows for IConfiguration to be injected making it easy to access from within ConfigureService() and Configure() methods.
What is the best practice way for gaining access to configuration?
There is an overload on some builder methods (i.e. ConfigureLogging() ConfigureAppConfiguration() ConfigureServices() that allows for a WebHostBuilderContext to be passed into the Action.
The WebHostBuilderContext provides access to the HostingEnvironment and Configuration
public class HostingStartupConfiguration : IHostingStartup
{
public void Configure(IWebHostBuilder builder)
{
builder
.ConfigureLogging((context, builder) =>
{
// clear providers set from host application
if (context.HostingEnvironment.IsDevelopment())
{
...
}
})
.ConfigureAppConfiguration((context, builder) =>
{
if (context.HostingEnvironment.IsDevelopment())
Console.WriteLine("we are in dev mode");
...
})
.ConfigureServices((context, services) =>
{
...
// get assemblies based on configuration to load as Application Parts
var assemblies = GetControllerAssemblies(context.Configuration);
// register controllers application parts from external assemblies
foreach (var assembly in assemblies)
{
builder.AddApplicationPart(assembly);
}
...
});
}

How to validate all registered types in ASP.NET Core DI?

I want to check that the type registrations I established in Startup.cs are all valid at runtime (either when starting up the service or as part of a test suite). There's a feature like this in Lamar and other containers.
ASP.NET Core 3.x actually introduced a feature for scope and provider validation. Both of these are useful in different contexts (see the below post and sample code).
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.UseDefaultServiceProvider((context, options) =>
{
options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
options.ValidateOnBuild = true;
});
https://andrewlock.net/new-in-asp-net-core-3-service-provider-validation/
You can iterate the services that you want to validate, and try to initialize a service with GetRequiredService<T>. It will throw an exception if there is something wrong. More info on
https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.serviceproviderserviceextensions.getrequiredservice?view=aspnetcore-2.2
The IServiceCollection is actually enumerable over ServiceDescriptor which contains type information on the registered service and implementation. The service collection isn't usually registered, but it should be possible to capture both the service collection and service provider in a hosted service.
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddServicesValidation();
}
The right extension method can capture the services collection without actually registering it (which feels "safer").
public static class ValidateServicesExtensions
{
public static IServiceCollection AddServicesValidation(this IServiceCollection services)
{
services.AddHostedService<ValidateServices>(provider => new ValidateServices(services, provider));
return services;
}
}
Now, the hosted service can iterate over the registered services & implementations. Although, this code bombs on the first generic IOptions<TOption>, but I'm sure we can figure something out?
ValidateServices.cs
public class ValidateServices : BackgroundService
{
private readonly IServiceCollection services;
private readonly IServiceProvider provider;
public ValidateServices(
IServiceCollection services,
IServiceProvider provider
)
{
this.services = services;
this.provider = provider;
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
using var scope = provider.CreateScope();
foreach (var service in services)
{
_ = scope.ServiceProvider.GetRequiredService(service.ServiceType);
}
return Task.CompletedTask;
}
}

MassTransit 5.2, SignalR: How can i get the IHubContext inside my Consumer?

My main problem is to get the right instance of the SignalR hub.
Context: Im building a webapplication which communicates with a couple of external systems. CRUD operations in my application result in updating the databases of the external systems.
In this example i have 3 services running:
ExternalSystem | StateMachine | .NET CORE WebAPI
When i post the 'create employee' form, a RabbitMQ message will be sent from the WebAPI to the statemachine. The statemachine then sends a couple of create messages to my external system service which updates the database. Thereafter, it updates the statemachine to keep track of the createoperation.
Form -> API -> StateMachine -> ExternalSystem -> StateMachine -> API
So far so good. Now i would like to use SignalR to send the status updates to the client. So i've implemented this consumer in the API:
public class UpdatesConsumer :
IConsumer<IExternalSystemUpdateMessage>
{
private readonly IHubContext<UpdatesHub> _updaterHubContext;
public UpdatesConsumer(IHubContext<UpdatesHub> hubContext)
{
_updaterHubContext = hubContext;
}
public Task Consume(ConsumeContext<IExternalSystemUpdateMessage> context)
{
//return _updaterHubContext.Clients.Group(context.Message.CorrelationId.ToString()).SendAsync("SEND_UPDATE", context.Message.Message);// this.SendUpdate(context.Message.CorrelationId, context.Message.Message);
return _updaterHubContext.Clients.All.SendAsync("SEND_UPDATE", context.Message.Message);
}
}
This is my SignalR hub:
public class UpdatesHub :
Hub
{
public Task SendUpdate(Guid correlationId, string message)
{
return Clients.Group(correlationId.ToString()).SendAsync("SEND_UPDATE", message);
}
}
And this is how the Bus and consumer is instantiated:
public void ConfigureServices(IServiceCollection services)
{
_services = services;
services.AddMvc();
services.AddSignalR();
//services.AddSingleton<IHubContext<UpdatesHub>>();
WebAPI.CreateBus();
}
public static IServiceCollection _services;
static IBusControl _busControl;
public static IBusControl Bus
{
get
{
return _busControl;
}
}
public static void CreateBus()
{
IRMQConnection rmqSettings = Config.GetRMQConnectionConfig("rmq-settings.json", "connection");
_busControl = MassTransit.Bus.Factory.CreateUsingRabbitMq(x =>
{
var host = x.Host(BusInitializer.GetUri("", rmqSettings), h =>
{
h.Username(rmqSettings.UserName);
h.Password(rmqSettings.Password);
});
x.ReceiveEndpoint(host, "externalsystems.update",
e => { e.Consumer(() => new UpdatesConsumer((IHubContext<UpdatesHub>)Startup.__serviceProvider.GetService(typeof(IHubContext<UpdatesHub>)))); });
});
TaskUtil.Await(() => _busControl.StartAsync());
}
=========================================================================
So the problem is that _updaterHubContext.Clients in my Consumer class, always turn out to be empty. I've tested accessing the hub in a controller, and the clients do show up:
public class TestController : Controller
{
private readonly IHubContext<UpdatesHub> _hubContext;
public TestController(IHubContext<UpdatesHub> hubContext)
{
_hubContext = hubContext;
}
[HttpGet]
[Route("api/Test/")]
public IActionResult Index()
{
return View();
}
}
How can i get the right instance of the hub in my Consumer class? Or how can i access the IServiceCollection that .net is using?
Thnx in advance!
You can register your consumer so that MassTransit will resolve it from the IServiceProvider using the support provided in the MassTransit.Extensions.DependencyInjection package.
x.ReceiveEndpoint(host, "externalsystems.update", e =>
{
e.Consumer<UpdatesConsumer>(_serviceProvider);
});
Be sure to register your UpdatesConsumer in the container as well. This should resolve a new instance of the consumer for each message received on the endpoint.
Why not register Bus using Microsoft Dependency Injection. It should fix your issue, it will Resolve your consumer using IServiceProvider

FluentSecurity and Ninject

Error activating IntPtr
I'm trying to configure FluentSecurity (v.1.4) with Ninject (v.3) in an ASP.NET MVC 4 application.
I can't set up the ResolveServicesUsing() configuration expression without throwing the above error.
SecurityConfigurator.Configure(
configuration =>
{
configuration.ResolveServicesUsing(
DependencyResolver.Current.GetServices,
DependencyResolver.Current.GetService);
...
I've also tried using another overload for ResolveServicesUsing()
configuration.ResolveServicesUsing(
type => DependencyResolver.Current.GetServices(type));
FluentSecurity needs to be configured with Ninject to inject the method for finding my users' roles and also for the PolicyViolationHandler implementations.
UPDATE
I've found I can leave out the offending lines and still have my GetRolesFrom() implementation called (hurrah):
configuration.GetRolesFrom(
() =>
((IPersonManager)DependencyResolver
.Current
.GetService(typeof(IPersonManager)))
.GetCurrentUserRoles());
I still can't get my PolicyViolationHandler to work, however:
public class RequireRolePolicyViolationHandler : IPolicyViolationHandler
{
public ActionResult Handle(PolicyViolationException exception)
{
return new RedirectToRouteResult(
new RouteValueDictionary(
new
{
action = "AccessDenied",
controller = "Home"
}));
}
}
I'm doing the binding in a NinjectModule like this:
public class SecurityModule : NinjectModule
{
public override void Load()
{
this.Kernel.Bind<IPolicyViolationHandler>()
.To<RequireRolePolicyViolationHandler>();
}
}
Error activating IntPtr
Unfortunately you havn't posted the complete StackTrace. But usually you will get this exception when injecting a Func to some class without having a binding or using the Factory extension.
I use Fluent Security with Ninject as IOC container.
In your Fluent Security configuration, you need to set the service locator to the NinjectServiceLocator.
public static void Configure(IKernel kernel)
{
var locator = new NinjectServiceLocator(kernel);
ServiceLocator.SetLocatorProvider(() => locator);
SecurityConfigurator.Configure(
configuration =>
{
configuration.GetAuthenticationStatusFrom(() => HttpContext.Current.User.Identity.IsAuthenticated);
....
}
You can get the locator here.
Hope this helps