views:

868

answers:

3

I'd like to use interception with Unity, here is my code :

UnityContainer container = new UnityContainer();
container.AddNewExtension<Interception>();
container.RegisterType<T, T>();
container.Configure<Interception>().SetDefaultInterceptorFor<T>(new VirtualMethodInterceptor());
return container.Resolve<T>();

If T is a class with a constructor with parameters (an an empty constructor) an exception is thrown when I call Resolve, else it works. How can I intercept a type who has a non empty constructor ?

Update

UnityContainer container = new UnityContainer();
container.AddNewExtension<Interception>();
container.RegisterType<T, T>();
container.Configure<InjectedMembers>().ConfigureInjectionFor<T>(new InjectionConstructor());
container.Configure<Interception>().SetDefaultInterceptorFor<T>(new VirtualMethodInterceptor());
return container.Resolve<T>();

This code works, but what if I'd like to use a constructor with argument ?

I've tried this :

public static T Resolve<T>(object param)
{
    UnityContainer container = new UnityContainer();
    container.AddNewExtension<Interception>();
    container.RegisterType<T, T>();
    container.Configure<InjectedMembers>().ConfigureInjectionFor<T>(new InjectionConstructor(param));
    container.Configure<Interception>().SetDefaultInterceptorFor<T>(new VirtualMethodInterceptor());
    return container.Resolve<T>();
}

And in my code :

var service = Resolve<MyService>(4);

And I'm back with the same exception as earlier...

A: 

Use the InjectionConstructor attribute as described here.

JP Alioto
I don't want to inject anything, I just want to create the interceptor which will call the empty constructor of T.
Nicolas Dorier
+1  A: 

Unity will pick the constructor with the most arguments, so you have a few options:

1) Use configuration to specify using the no arg constructor like so:

Container.Configure<InjectedMembers>()
    .ConfigureInjectionFor<MyService>(new InjectionConstructor());

2) Annotate your object

public class MyService
{
    [InjectionConstructor]
    public MyService()
    {
    }

    public MyService(int arg1)
    {     
    }
}

3) override the DefaultUnityConstructorSelectorPolicy with your own that chooses the no arg constructor if it exists.

Michael Valenty
It works, but if I want to use MyService(int arg1), it throws (see my question, I've updated)
Nicolas Dorier
+1  A: 

It's a bug

Nicolas Dorier