c# - How to make Unity call a method after creating an object instance but before it is injected anywhere -
i'm using unity dependency injection. i'd achieve this:
public interface myinterface { void mymethod(); }
when building unity container:
mycontainer.registertype<myinterface, myconcretetype>(); mycontainer.addpostconstructor(x => (x myinterface)?.mymethod());
is possible? there better/more elegant way?
another way - register implementations via special factory , use it:
class factory { iunitycontainer _container; public factory(iunitycontainer container) { _container = container; } public void register<ttype>() ttype : myinterface { mycontainer.registertype<myinterface, ttype>(new injectionfactory(c => { var result = c.resolve<ttype>(); result.mymethod(); return result; })); } public myinterface get() { _container.resolve<myinterface>(); } }
...
public testclass { factory _factory; public testclass(factory factory) { _factory = factory; _factory.register<myconcretetype>(); } public void testmethod() { var service = _factory.get(); } }
so, future implementations must registered in factory. still there no guarantee method mymethod
implemented correct or implemented @ all.
Comments
Post a Comment