poindexter12
poindexter12

Reputation: 1783

Unity automatic injection

I have already done the following:

  1. Register an instance of my Logger in unity via a ILogger interface.
  2. 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.

Upvotes: 4

Views: 1698

Answers (3)

TrueWill
TrueWill

Reputation: 25523

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.

Upvotes: 0

Brad Cunningham
Brad Cunningham

Reputation: 6501

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

Upvotes: 2

Mark Seemann
Mark Seemann

Reputation: 233135

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.

Upvotes: 1

Related Questions