This project is read-only.

instanceCreator for generic?

Aug 2, 2013 at 4:03 PM
Hi there,

Currently I am using
container.Register<IRepository<User, int>>(() => new DataRepository<User>(MvcApplication.CreateContext()));

to register the classes. If I have a List<Type> to contain all the types, how can I do it without repeat all the code?

Thanks in adanvce
Aug 2, 2013 at 6:46 PM
Prevent using the delegate registration, but rely on the container's auto-wiring facilities:
// using SimpleInjector.Extensions;

container.Register<IContext>(
    () => MvcApplication.CreateContext());

container.RegisterOpenGeneric (
    typeof(IRepository<,>),
    typeof(DataRepository<>));
The RegisterOpenGeneric method allows mapping an open generic abstraction to an open generic implementation. By registering the Context in the container, that type can automatically be injected into the DataRepository's constructor (assuming you have one constructor with an argument of type IContext).

Now when you ask for an IRepository<User, int>, the container will return an DataRepository<User> for you (assuming that DataRepository<T> implements IRepository<T, int> of course).
Marked as answer by dot_NET_Junkie on 2/26/2014 at 1:41 PM