Reputation: 17445
Given this example implementation of ConfigureServices
:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<SomeComponent>();
services.AddMvc(config =>
{
config.OutputFormatters.Add(new CustomFormatter(/* HELP! */));
});
}
I need to pass an instance of SomeComponent
(hopefully only a single one will exist) to the constructor of my custom formatter. How can resolve such an instance from within the ConfigureServices
implementation?
Upvotes: 1
Views: 385
Reputation: 10889
You can build the service provider in advance and use it like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<SomeComponent>();
var provider = services.BuildServiceProvider();
var item = provider.GetService<SomeComponent>();
services.AddMvc(config =>
{
config.OutputFormatters.Add(new CustomFormatter(item));
});
}
Upvotes: 2
Reputation: 33897
I know that some developers see the service locator pattern as an anti-pattern. But there are cases where it's the right tool for the job. This is probably one of those cases. You could solve your issue like so:
public void ConfigureServices(IServiceCollection services,
IHttpContextAccessor contextAccessor)
{
services.AddSingleton<SomeComponent>();
var someComponent = contextAccessor.HttpContext.RequestServices.GetServices<SomeComponent>(); //service locator pattern
services.AddMvc(config =>
{
config.OutputFormatters.Add(new CustomFormatter(someComponent));
});
}
The above example is for RC2 I notice that in RC1 the key line is a bit different and would be like this:
var someComponent = contextAccessor.HttpContext.ApplicationServices.GetService<SomeComponent>();
Upvotes: 1