Question

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);
    });
}
Was it helpful?

Solution

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<,,>));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top