根据AspNetCore中的某些条件添加依赖项

时间:2019-04-10 17:54:36

标签: c# asp.net-core

如果要满足某些条件,我想添加一个依赖项,但是要测试该条件,我需要使用IServiceProvider。有什么好方法吗?

这是我的代码,但是可以肯定的是,由于许多原因,该代码无法正常工作,但这就是我到目前为止所取得的成就:

我也不想两次重建IServiceCollection

public static IServiceCollection AddWithCondition<TInterface, TImplementation>(
    this IServiceCollection collection, 
    Func<IServiceProvider, bool> validateFunc,
    ServiceLifetime lifetime,
    Func<IServiceProvider, TImplementation> factory)
    where TImplementation :  class
{ 
    collection.Add(new ServiceDescriptor(typeof(TInterface), p => validateFunc(p) ? factory(p) : default(TImplementation), lifetime));
    var descriptorToRemove = collection.FirstOrDefault(d => d.ServiceType == typeof(TInterface) && d.ImplementationInstance == default);
    if (descriptorToRemove != null)
        collection.Remove(descriptorToRemove);
    return collection;
}

1 个答案:

答案 0 :(得分:0)

您似乎在应用程序启动/配置阶段中应用了域逻辑,正如注释中指出的那样,这是一种代码味道。建议您重构应用程序以使用工厂模式来创建所请求服务的实例。工厂可以利用依赖注入本身来执行条件逻辑。例如:

服务:

public interface IService { }

public class FooService : IService { }

// And more implementations of IService...

服务工厂:

public interface IServiceFactory
{
    IEnumerable<IService> GetServices();
}

public class ServiceFactory : IServiceFactory
{
    public ServiceFactory(MyWebservice myWebservice) { }

    public IEnumerable<IService> GetServices()
    {
        // Use MyWebservice to conditionally create the desired IService instances
        // or use any other type of logic.
    }
}

IServiceFactory添加到依赖项注入容器后,可以对其进行注入并使用它来解析IService实例:

public class SomeController
{
    public SomeController(IServiceFactory serviceFactory) { }

    public IActionResult Get()
    {
        var services = _serviceFactory.GetServices();
        // Do something with the created IService instances...
    }
}