0

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...

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It works, but if I want to use MyService(int arg1), it throws (see my question, I've updated)
1

It's a bug

Comments

0

Use the InjectionConstructor attribute as described here.

1 Comment

I don't want to inject anything, I just want to create the interceptor which will call the empty constructor of T.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.