简体   繁体   中英

Is there a .NET Framework equivalent to .NET Core's IControllerActivator?

The book Dependency Injection: Principles and Practices describes how to set up dependency injection using an IControllerActivator implementation. In an ASP.NET Core project, this can be added to the program's services in the Startup.ConfigureServices() method. This all makes sense.

However, ASP.NET Framework (4.7.2) doesn't use the same model. There is no Startup class. There is an IControllerActivator interface, but it's in a different namespace ( System.Web.Mvc vs Microsoft.AspNetCore.Mvc.Controllers ), has different members, and when I try to call the following:

public static void Register(HttpConfiguration config) {
    config.Services.Add(typeof(IControllerActivator), new CompositionRoot());

...I get the exception The service type IControllerActivator is not supported.

The ultimate goal here is to be able to define parameter-using constructors on ApiControllers and have the controller be instantiated by resolving it from a DI container when the service receives a request.

How can I implement this pattern in .NET Framework?

I'm assuming this is an ASP.NET MVC app, so you use a DependencyResolver to do it.

I don't know what IoC Container you are using, but all the major ones have builtin support for it through their nuget packages. For example, here isAutoFac docs , and here is StructureMap docs for integrating with ASP.NET MVC.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM