bbqchickenrobot bbqchickenrobot - 1 year ago 112
C# Question

Get Generic Argument Type in Open Registration with Simple Injector

I am attempting to get the generic argument type in an open registration without having to use object. Here is the code snippet:

container.Register(typeof(IRepository<>), ()=> {
return new Repository<object>("connString");
}, Lifestyle.Transient);

So in the lambda I would like to instantiate the repository with the specific generic type instead of using object.

Answer Source

The overloads of Register that take in a lambda don't support generics. This is because Simple Injector can't determine the type for you, which is something you probably already found out.

There are multiple solutions, but what is probably the simplest is to extract the connection string parameter into a data object, and let the repository depend on that:

public class ConnectionStringSettings
    public string ConnectionString {get;set;}

container.RegisterSingleton(new ConnectionStringSettings { ConnectionString = "constr" });
container.Register(typeof(IRepository<>), typeof(Repository<>));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download