I have just started using Unity and the interception capabilities. I created a prototype to verify the limitation or capabilities and it seems to me that in order to intercept a method there are several condition that must be met. In particular it seems to me that the class or interface must be resolved through the container. Is that correct? Is there any method out there that let’s me do this without this requirement.
I may be misinterpreting how to use this properly as there is alot of older and partial information out there without good working examples.
I will update with some code. Please keep in mind there are thousands upon thousands of lines of code in this thing so changing this bad design is not an option and out of scope of this current project.
public interface IApoClass
{
[LoggingCallHandler]
void SomeAbstractAopMethod(string abstractparam);
[LoggingCallHandlerAttribute]
void SomeVirtualAopMethod(string virtualparam);
}
public abstract class AbstractAopClass : IApoClass
{
public abstract void SomeAbstractAopMethod(string whatthe);
public virtual void SomeVirtualAopMethod(string abstractparam)
{
//essentiall do nothing
return;
}
}
public class NonAbstractAopMethod : AbstractAopClass
{
public override void SomeAbstractAopMethod(string whatthe)
{
Console.Write("I am the only enforced method");
}
}
The container:
container.AddNewExtension<Interception>();
//container.Configure<Interception>().SetInterceptorFor<IFrameworkInterceptionTest>(new InterfaceInterceptor());
container.Configure<Interception>().SetInterceptorFor<IApoClass>(new InterfaceInterceptor());
The calling code:
//resolve it despite it not having and definition, but we've wired the container for the interface implemented by the abstract parent class
var nonabstractmethod = DependencyResolver.Current.GetService<NonAbstractAopMethod>();
nonabstractmethod.SomeAbstractAopMethod("doubt this works");
nonabstractmethod.SomeVirtualAopMethod("if the above didn't then why try");
Your assumption is correct: if you wish to use interception you need to resolve the object through the container so Unity can create a proxy object or return a derived type.
Unity Interception Techniques does a good job of explaining how it works.
If I understand you correctly, you want to perform interception for interface methods while minimizing changes to the existing system.
You should be able to wire up the interception. First register the interface and the concrete type you want to map to and then set the interception:
If you need to map the interface to multiple concrete types you can do that by using a name: