Web框架 --- 一个Interface注入多个实例
- 如何注入
- 如何获取
如何注入
class MyImplA : IMyinterface
{public string ImplementationName => Consts.MyImplA;
}
class MyImplB : IMyinterface
{public string ImplementationName => Consts.MyImplB;
}
class DependencyInjection
{public DP(){services.AddSingleton<IMyinterface, MyImplA>();services.AddSingleton<IMyinterface, MyImplB>():}
}
如何获取
class MyClass
{private readonly IEnumerable<IMyinterface> _myInterfaces;public MyClass(IEnumerable<IMyInterface> myInterfaces){_myInterfaces = myInterfaces}public GetInplementation() {var myImplementation = _myInterfaces.FirstOrDefault(handler => handler.ImplementationName.Equals(Consts.MyImplB));}
}
Or
class MyClass
{private readonly IEnumerable<IMyinterface> _myInterfaces;public MyClass(IEnumerable<IMyInterface> myInterfaces){_myInterfaces = myInterfaces}public GetInplementation() {var myImplementation = _myInterfaces.FirstOrDefault(handler => handler.GetType() == typeof(MyImplB));}
}