[英]DI: Different implementations of the same interface for the different controllers
I have two controllers:我有两个控制器:
namespace V1
{
[ApiVersion("1.0")]
public class SomeController : Controller
{
public SomeController(IProvider provider) { }
}
}
namespace V2
{
[ApiVersion("2.0")]
public class SomeController : Controller
{
public SomeController(IProvider provider) { }
}
}
And the following services:以及以下服务:
public interface IStorage { }
public interface IProvider { }
public class V1Storage : IStorage { }
public class V2Storage : IStorage { }
public class Provider : IProvider
{
public Provider(IStorage storage) { }
}
For the first version of controller I need to use V1Storage
, for the second - V2Storage
.对于控制器的第一个版本,我需要使用V1Storage
,对于第二个版本 - V2Storage
。 I know there is a way to replace DefaultControllerFactory
but what is the best way to implement it?我知道有一种方法可以替换DefaultControllerFactory
但实现它的最佳方法是什么?
Use AddControllersAsServices to help with this.使用AddControllersAsServices来帮助解决这个问题。 The documentation describes that this:该文档描述了这一点:
Registers discovered controllers as services in the IServiceCollection.将发现的控制器注册为 IServiceCollection 中的服务。
Here's a complete example:这是一个完整的例子:
void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddControllersAsServices();
services.AddTransient(sp => new V1.SomeController(new Provider(new V1Storage())));
services.AddTransient(sp => new V2.SomeController(new Provider(new V2Storage())));
}
By re-registering V1.SomeController
and V2.SomeController
after the call to AddControllersAsServices
, you take control of exactly how they are constructed, passing in an IProvider
implementation configured with the required IStorage
implementation for each controller.通过在调用AddControllersAsServices
之后重新注册V1.SomeController
和V2.SomeController
,您可以准确地控制它们的构造方式,传入一个IProvider
实现,该实现配置为每个控制器所需的IStorage
实现。
Andrew Lock describes this approach in Controller activation and dependency injection in ASP.NET Core MVC . Andrew Lock 在 ASP.NET Core MVC中的控制器激活和依赖注入中描述了这种方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.