I have already done the following:
- Register an instance of my Logger in unity via a ILogger interface.
- Created an interface, ILoggableObject, that has a method, Hook(ILogger logger), to inject my logger.
I would like to accomplish this:
Everytime I ask for any resolution from unity, if that object implements ILoggableObject, automatically inject the ILogger interface via the Hook method.
I think this is possible via interception or policies?
Any help would be awesome.
3 Answers 3
What you are looking for is TypeInterception in Unity. See here: http://msdn.microsoft.com/en-us/library/ff660861(PandP.20).aspx
Also here http://msdn.microsoft.com/en-us/library/ff660848(v=PandP.20).aspx
You want to intercept the call to the constructor and inject the Logger on behalf of the calling code without them being any wiser.
While I haven't done it before I believe you can do what you want using Intercept.NewInstance() http://msdn.microsoft.com/en-us/library/ff662093(PandP.20).aspx
Comments
That is a horrible way to (attempt to) do Dependency Injection. Use Constructor Injection instead and inject (via the constructor) the ILogger into the consumer that right now has the Hook method.
4 Comments
While I really like Unity and IoC/DI, I'm not sure that it is the right tool to accomplish what you want to do.
You might consider looking at aspect-oriented programming using PostSharp or a similar tool. This would allow you to add logging or other cross-cutting concerns without changing the classes being instrumented.
Comments
Explore related questions
See similar questions with these tags.
Hookmethod to a public constructor (with the same arguments).