[Announcement] Generic Host restricts Startup constructor injection
See original GitHub issueTLDR: The only types the generic Host supports for Startup constructor injection are IHostEnvironment
, IWebHostEnvironment
, and IConfiguration
. Applications using WebHost are unaffected.
In 3.0 we’ve re-platformed the web stack onto the generic host library. You can see the change in Program.cs in the templates:
2.x: https://github.com/aspnet/AspNetCore/blob/5cb615fcbe8559e49042e93394008077e30454c0/src/Templating/src/Microsoft.DotNet.Web.ProjectTemplates/content/EmptyWeb-CSharp/Program.cs#L20-L22 3.0: https://github.com/aspnet/AspNetCore/blob/b1ca2c1155da3920f0df5108b9fedbe82efaa11c/src/ProjectTemplates/Web.ProjectTemplates/content/EmptyWeb-CSharp/Program.cs#L19-L24
One key behavior change here is that Host only uses one dependency injection container to build the application, as opposed to WebHost that used one for the host and one for the app. As a result the Startup constructor no longer supports custom service injection, only IHostEnvironment
, IWebHostEnvironment
, and IConfiguration
can be injected. This change was made to avoid DI issues such as duplicate singleton services getting created.
Mitigations:
Inject services into Startup.Configure:
public void Configure(IApplicationBuilder app, IOptions<MyOptions> options)
[We’ll add more based on requests for specific scenarios.]
Issue Analytics
- State:
- Created 4 years ago
- Reactions:14
- Comments:55 (16 by maintainers)
Ok. Seems to be limiting. Just seems that logging is so important that it should be created up front and allowed to be used anywhere. Is it possible to create a logger to be used during configuration?
This is a real disappointment. By using the WebHost container, I was able to register a number of classes as “Binding Services” or “Startup Services” via attributes. Then I could use
IEnumerable<IStartupBinder>
andIEnumerable<IStartupService>
inConfigureServices
andConfigure
respectively and my startup looked like this:Which our team found to be a very clean design. We had a chuckle at the response that logging is simply “not supported in this model”. Please reconsider whether this is the ideal way forward.
We certainly were not confused by the WebHost having a separate container. Maybe documentation was the answer instead of this backwards-incompatible change…