Asp.net core 基于条件解析服务的DI
我有一个商店,有以下两种商店Asp.net core 基于条件解析服务的DI,asp.net-core,.net-core,Asp.net Core,.net Core,我有一个商店,有以下两种商店 interface IStore {} class AStore : IStore {} class BStore : IStore {} 然后我有一个服务 public Service : IService { public Service(IStore store) {} } 这意味着我们可以根据enum存储的条件通过AStore或BStore enum Store { A, B } if Store.A => return AStore
interface IStore {}
class AStore : IStore {}
class BStore : IStore {}
然后我有一个服务
public Service : IService
{
public Service(IStore store) {}
}
这意味着我们可以根据enum存储的条件通过AStore或BStore
enum Store { A, B }
if Store.A => return AStore
if Store.B => return BStore
在控制器中,我有一个操作,将存储作为参数传递,并获取一个服务实例以继续执行某些操作
比如说
public Task Get(Store store)
{
// How I can get Service instance with Store parameter which depends on IStore?
}
问题是我如何利用ASP.Net内核中的DI来解决依赖于IStore的服务?好的,这样您就可以实现这样的功能了
interface IStore<T> where T : StoreFactoryBase
{
string DoSomething();
}
services.AddScoped(typeof(IStore<>), typeof(Store<>));
private readonly IStore<A>storeA;
private readonly IStore<B>storeB;
SomeController(IStore<A>storeeA,IStore<B>storeB)
{
this.StoreA =storeeA;
this.storeB =storeB;
}
现在,您可以将基类实现为以下任一抽象类
public abstract class StoreFactoryBase
{
public abstract string DoSomething();
}
现在是DI部分,当您在startup类中注入您的服务时,它将如下所示
interface IStore<T> where T : StoreFactoryBase
{
string DoSomething();
}
services.AddScoped(typeof(IStore<>), typeof(Store<>));
private readonly IStore<A>storeA;
private readonly IStore<B>storeB;
SomeController(IStore<A>storeeA,IStore<B>storeB)
{
this.StoreA =storeeA;
this.storeB =storeB;
}
好的,你可以实现这样的东西
interface IStore<T> where T : StoreFactoryBase
{
string DoSomething();
}
services.AddScoped(typeof(IStore<>), typeof(Store<>));
private readonly IStore<A>storeA;
private readonly IStore<B>storeB;
SomeController(IStore<A>storeeA,IStore<B>storeB)
{
this.StoreA =storeeA;
this.storeB =storeB;
}
现在,您可以将基类实现为以下任一抽象类
public abstract class StoreFactoryBase
{
public abstract string DoSomething();
}
现在是DI部分,当您在startup类中注入您的服务时,它将如下所示
interface IStore<T> where T : StoreFactoryBase
{
string DoSomething();
}
services.AddScoped(typeof(IStore<>), typeof(Store<>));
private readonly IStore<A>storeA;
private readonly IStore<B>storeB;
SomeController(IStore<A>storeeA,IStore<B>storeB)
{
this.StoreA =storeeA;
this.storeB =storeB;
}
一种方法是将键控服务与自定义委托一起使用。一种方法是将键控服务与自定义委托一起使用。