3
votes

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.

3
Why don't you use the constructor injection, which is the default mechanism? Simply rename the Hook method to a public constructor (with the same arguments). - Steven
Why not just pass ILogger into whatever objects ctor that needs to use the logging behavior? - Aaron McIver
That is how I was doing it. The problem with that approach is when your objects start using multiple interfaces, you end up with a constructor that has 10 parameters. Then, another developer who wants to inherit from that base class has to supply all of the constructor parameters that he / she has no need to see. - poindexter12
You can use Named parameter for calling constructor to avoid this. - Saeed Amiri
@poindexter12: You should never have a constructor that accepts 10 parameters, 5-6 at most. If you do, then theres clearly something wrong with it. And a class like that should be refactored into smaller parts. - Robin Orheden

3 Answers

2
votes

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

1
votes

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.

0
votes

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.