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

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

android - CoordinatorLayout, FAB and container layout conflict -