Automatically resolve Interface<T> to Implementation<T> in StructureMap (differ only by generic type T) Automatically resolve Interface<T> to Implementation<T> in StructureMap (differ only by generic type T) asp.net asp.net

Automatically resolve Interface<T> to Implementation<T> in StructureMap (differ only by generic type T)


Turns out there is no fancy method to call, or no fancy wiring to do, you just use For and Use (the non generic versions):

public class DataRegistry : Registry{    public DataRegistry()    {        For(typeof (IRepository<>)).Use(typeof(Repository<>));    }}

When I inject a IRepository<Person> it is being resolved as a Repository<Person> now.

I encountered error 104 saying Repository wasn't pluggable for IRepository. This was because Repository was marked abstract. Making it non-abstract fixed that error and it is working as desired.


I suggest you to take a look at the AddAllTypesOf method. I had some similar code and achieved my objectives by using it (and kept the auto register feature working).

In your case, you should just change

For<IRepository<Person>>().Use<Repository<Person>>();For<IRepository<Product>>().Use<Repository<Product>>();For<IRepository<Order>>().Use<Repository<Order>>();For<IRepository<Whatever>>().Use<Repository<Whatever>>();

to

AddAllTypesOf(typeof(IRepository<>));

In the end, your container will be similar to:

return new Container(x =>        {            x.Scan(y =>            {                y.TheCallingAssembly();                y.AddAllTypesOf(typeof(IRepository<>));                y.WithDefaultConventions();            });        });


Here is an example. Structure map will allow you to do both also.

 //IRepository For<IMemberRepository>().Add<MemberRepository>(); //IRepository<T> For<IRepository<Member>>().Add<MemberRepository>();

Then it is useful to ask for the types by just knowing the generic type at runtime:

Type repositoryType = typeof(IRepository<>).MakeGenericType(modelType);IocResolve.Resolve(repositoryType);