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. Can't figure out how to pass in <> generic interfaces using 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:

 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). 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归因
不隶属于 StackOverflow
scroll top