How to do post processing on an object after Unity has resolved it?
I have what I think is a fairly common problem, but I cannot seem to find a good way to solve it.
Let's say I have an interface IFoo and I use Unity to create an instance of Foo:
class Foo : IFoo {}
IFoo foo = Container.Resolve<IFoo>();
After initialization I would like to to call a method for post-processing FooPostProc that takes in a Foo object (not IFoo interface) For example I would like
return Container.Resolve<IFoo>();
to be equivalent to:
void FooPostProc(Foo obj){}
Foo obj = new Foo();
FooPostProc(obj) ;
return obj ;
Essentially I would like to specify in the Unity container configuration (xml preferably) a method to call on the specific instance of the object immediately aft开发者_如何学Cer the object is created. I am doing this as I am not able to add additional constructors to the original Foo object.
I am seeing some hints that it may be possible using Unity Interception, but it looks very involved. Is there a reasonably simple way this can be accomplished using Unity configuration ?
There's two options here.
If you're not otherwise using it, Method injection will work - you can configure methods to call on the instance as it's created. There's no guarantee of ordering between methods if you're using multiple injection methods, but it works. This only works if the post processing method is a method of the object you've created.
Via the API, you do:
container.RegisterType<IFoo, Foo>(
// ... constructor, property configuration
new InjectionMethod("FooPostProc"));
or in XML:
<register type="IFoo" mapTo="Foo">
<method name="FooPostProc" />
</register>
You can also pass parameters to the method just like you can to the constructor.
The other option is to use the undocumented, but included, BuilderAwareStrategy. You'll need to write a small Unity extension to add the strategy to the container.
Once you do, you can then implement Microsoft.Practices.ObjectBuilder2.IBuilderAware interface. At the end of the resolve process, the container will call IBuilderAware.OnBuiltUp. Again, this requires you implement the method on the type that's being resolved.
For example:
public class myClass : IBuilderAware
{
.. regular class implementation..
public void OnBuiltUp(NamedTypeBuildKey buildkey) {}
public void OnTearingDown() {}
}
If the post-processing method isn't on the object being resolved, the quickest thing would be to use an InjectionFactory (API only, no XML) and do whatever you want.
精彩评论