我有一家商店,有以下两种商店
interface IStore {}
class AStore : IStore {}
class BStore : IStore {}
然后我有服务
public Service : IService
{
public Service(IStore store) {}
}
这意味着我们可以根据枚举商店的条件通过AStore或BStore
enum Store { A, B }
if Store.A => return AStore
if Store.B => return BStore
在控制器中,我有一个动作将Store作为参数传递并获取Service实例以进行某些操作
例如
public Task Get(Store store)
{
// How I can get Service instance with Store parameter which depends on IStore?
}
问题是我如何利用ASP.Net Core中的DI解决依赖IStore的服务?
答案 0 :(得分:0)
好,这样您就可以实现
#define CC_LIST \
/* n */ \
X(1) \
X(2) \
#define CC(n) CC_##n
#define CC_1 1,2
#define CC_2 3,4
#define CALL_FUNCTION(...) (void) Coord(__VA_ARGS__);
int main()
{
#define X(n) CALL_FUNCTION(CC(n))
CC_LIST
#undef X
return 0;
}
然后
SELECT CONVERT('Ä Ê Í Õ Ø A B C D E ', 'US7ASCII', 'WE8ISO8859P1')
FROM DUAL;
CONVERT('ÄÊÍÕØABCDE'
---------------------
A E I ? ? A B C D E ?
}
现在您需要创建继承StoreFactoryBase的其他服务
即
interface IStore<T> where T : StoreFactoryBase
{
string DoSomething();
}
现在您可以将基类实现为这样的抽象类
class Store<T> : IStore<T> where T : StoreFactoryBase{
private readonly StoreFactoryBase instance = null;
Store()
{
instance = (T)Activator.CreateInstance(typeof(T));
}
public string DoSomething()
{
instance.DoSomething()
}
现在,当您在启动类中注入服务时,这里是DI部分,它将看起来像这样
public class A:StoreFactoryBase
{
Public virtual string DoSomething()
{
return "Hello from Class A";
}
}
public class B:StoreFactoryBase
{
Public virtual string DoSomething()
{
return "Hello from Class B";
}
}
现在,当您将服务注入控制器时,就这样说
public abstract class StoreFactoryBase
{
public abstract string DoSomething();
}
A将执行As方法,而B将执行Bs方法
更新
在您要切换方法/存储的条件下说
然后
services.AddScoped(typeof(IStore<>), typeof(Store<>));