如何在简单注入器中注册两种类型的泛型?

How to register generic with two types in Simple Injector?

这是我的界面,class:

 public interface IServiceFactory<T, Y> where T : class  where Y : class
{
     T Create(ModelStateDictionary modelState);
}

public class ServiceFactory<T, Y> : IServiceFactory<T, Y>
    where T : class
    where Y : class
{

    public T Create(ModelStateDictionary modelState)
    {
        var x = (T) Activator.CreateInstance(typeof (Y), new ModelStateWrapper(modelState));
        return x;
    }
}

Simple Injector 的容器寄存器:

  container.RegisterManyForOpenGeneric(typeof(IServiceFactory<, >), typeof(IServiceFactory<, >));

如何设置 Simple Injector 以使用包含多种类型的泛型?

Register(Type, IEnumerable<Assembly>)(v2 中的RegisterManyForOpenGeneric)允许批量注册。所以一般来说,您为 Register 提供一个开放的泛型类型和一个或多个 Assembly 实例,该方法将遍历程序集中的类型并注册所提供的泛型的所有非泛型实现类型。

您似乎想要的是将开放通用抽象映射到开放通用实现,以便在请求封闭通用抽象时返回封闭通用实现。

这是执行此操作的方法:

// Simple Injector v3.x
container.Register(typeof(IServiceFactory<,>), typeof(ServiceFactory<,>));

// Simple Injector v2.x
container.RegisterOpenGeneric(typeof(IServiceFactory<,>), typeof(ServiceFactory<,>));

顺便说一句,我已经阅读了您之前的问题,您似乎被 . The answerer correctly states that ModelState is an runtime value and you should not inject this runtime value in the constructor of a service. The use of a factory will only move the problem, because inside the factory you are still injecting the runtime value into the constructor of the service. This breaks the dependency graph and prevents you from verifying and diagnosing 您的对象图上的答案误导了。

在这种情况下,我建议简单地将 ModelState 传递给服务方法。