【问题标题】:Resolve DI of a Service based on condition根据条件解析服务的 DI
【发布时间】:2020-02-06 18:12:59
【问题描述】:

我有一个店铺,有以下2种店铺

interface IStore {}
class AStore : IStore {}
class BStore : IStore {}

那我有一个服务

public Service : IService 
{
    public Service(IStore store) {}
}

表示我们可以根据 enum 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 的 Service?

【问题讨论】:

标签: asp.net-core .net-core


【解决方案1】:

好的,所以你可以实现这样的东西

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()
  }

}

现在您需要创建继承 StoreFactoryBase 的不同服务

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();
    }

现在这是 DI 部分,当您在启动类中注入服务时,它看起来像这样

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;
}

A 将执行 As 方法,而 B 将执行 Bs 方法

更新

在你想切换方法/存储的条件下说

然后

if(storeA)
{
storeA.DoSOmething();
}
else StoreB.DoSOmething();

【讨论】:

    猜你喜欢
    • 2020-05-17
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 2016-11-09
    相关资源
    最近更新 更多