Friday, 15 May 2015

c# - Register Generic Type in StructureMap Based On Concrete Type -



c# - Register Generic Type in StructureMap Based On Concrete Type -

this similar question unity, applies structuremap instead.

i'm trying emulate behavior can configure in ninject, using unity instead.

i attempting utilize cached repository pattern, given next classes , interface:

public interface irepository<t> { t get(); } public class sqlrepository<t> : irepository<t> t : new() { public t get() { console.writeline("getting object of type '{0}'!", typeof(t).name); homecoming new t(); } } public class cachedrepository<t> : irepository<t> t : class { private readonly irepository<t> repository; public cachedrepository(irepository<t> repository) { this.repository = repository; } private t cachedobject; public t get() { if (cachedobject == null) { cachedobject = repository.get(); } else { console.writeline("using cached repository fetch '{0}'!", typeof(t).name); } homecoming cachedobject; } }

basically, time application uses irepository<t>, should instance of cachedrepository<t>. within of cachedrepository<t> should fetch actual sql repository of sqlrepository<t>. in ninject, have accomplished using following:

ninjectmodule.bind(typeof(irepository<>)).to(tyepof(sqlrepository<>)).wheninjectedexactlyinto(tyepof(cachedrepository<>)); ninjectmodule.bind(typeof(irepository<>)).to(tyepof(cachedrepository<>));

in structuremap, have accomplished binding non-generic repository following:

x.for<iwidgetrepository>().use<cachedwidgetrepository>().ctor<iwidgetrepository>().is<sqlwidgetrepository>();

unfortunately, ctor method not come overload not take generic.

...ctor(typeof(irepository<>))... // not exist! ...ctor<irepository<>>()... // compiler error!

i could register every possible instance manually:

x.for<irepository<widget>>().use<cachedrepository<widget>>().ctor<irepository<widget>>().is<sqlrepository<widget>>();

but not ideal.

edit: found stackoverflow question, reply appears out of date: structuremap no longer has typeinterceptor class inherit from, rather exposes iinterceptor interface, accepted reply in stackoverflow question isn't compatible here.

c# generics inversion-of-control ninject structuremap

No comments:

Post a Comment