简体   繁体   English

将开放的泛型类型绑定到Simple Injector中的方法

[英]Binding an open generic type to a method in Simple Injector

I'm trying to configure the SharpRepository project to also make use of SimpleInjector IOC framework as an IOC optioni in the framework but am stuck on porting some of the code. 我正在尝试配置SharpRepository项目,使其也将SimpleInjector IOC框架用作该框架中的IOC选项,但在移植某些代码时会遇到问题。 Can't figure out how to pass in <> generic interfaces using SimpleInjector. 无法弄清楚如何使用SimpleInjector传入<>通用接口。

2nd issue/question is how to get the generic arguments passsed into the context using simple injector. 第二个问题是如何使用简单的注入器将通用参数传递到上下文中。

public static void BindSharpRepository(this IKernel kernel, 
    ISharpRepositoryConfiguration configuration)
{
    kernel.Bind(typeof (IRepository<>)).ToMethod(context =>
    {
        var genericArgs = context.Request.Service.GetGenericArguments();
        return RepositoryFactory.GetInstance(genericArgs[0], configuration);
    });

    kernel.Bind(typeof(IRepository<,>)).ToMethod(context =>
    {
        var genericArgs = context.Request.Service.GetGenericArguments();
        return RepositoryFactory.GetInstance(genericArgs[0], 
            genericArgs[1], configuration);
    });

    kernel.Bind(typeof(ICompoundKeyRepository<,,>)).ToMethod(context =>
    {
        var genericArgs = context.Request.Service.GetGenericArguments();
        return RepositoryFactory.GetInstance(genericArgs[0], genericArgs[1], 
            genericArgs[2], configuration);
    });
}

The thing that comes the closest in Simple Injector is the following: Simple Injector中最接近的是:

 container.ResolveUnregisteredType += (s, e) =>
 {
      Type type = e.UnregisteredServiceType;
      if (type.IsGenericType && 
          type.GetGenericTypeDefinition() == typeof(IRepository<>))
      {
           var args = type.GetGenericArguments();

           e.Register(() => RepositoryFactory.GetInstance(args[0], configuration));
      }
 };

Another option is to move the creation of the repositories out of the RepositoryFactory class (if possible). 另一个选择是将存储库的创建移出RepositoryFactory类(如果可能)。 That could make it much easier, because in that case you could simplify the registration to the following: 这可以使它变得容易得多,因为在这种情况下,您可以将注册简化为以下内容:

// using SimpleInjector.Extensions;
container.RegisterOpenGeneric(typeof(IRepository<>), typeof(GenericRepository<>));
container.RegisterOpenGeneric(typeof(IRepository<,>), typeof(GenericRepository<,>));
container.RegisterOpenGeneric(typeof(ICompoundKeyRepository<,,>), 
    typeof(GenericCompoundKeyRepository<,,>));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM