How to use InterfaceInterceptor with NServiceBus UnityBuilder
- by David
I have a MessageHandler with a dependency declared as:
public IRepository<Person> PersonRepository {get;set;}
I set up my Unity container with:
IUnityContainer container = new UnityContainer();
container.AddNewExtension<Interception>();
container.RegisterType(typeof(IRepository<Person>), typeof(Example.Data.InMemory.Repository<Person>));
container.Configure<Interception>()
.AddPolicy("PersonAddAdvice")
.AddMatchingRule(new AddMatchingRule())
.AddCallHandler(new PersonAddedEventPublishingCallHandler());
container.Configure<Interception>()
.SetInterceptorFor<IRepository<Person>>(new InterfaceInterceptor());
Then I Init my endpoint with:
class EndpointConfig : IConfigureThisEndpoint, AsA_Publisher, IWantCustomInitialization
{
public void Init()
{
NServiceBus.Configure.With()
.Log4Net()
.UnityBuilder(ContainerConfig.LoadContainer())
.XmlSerializer();
}
}
(ContainerConfig.LoadContainer() returns the pre-configured IUnityContainer)
the problem is that the IRepository dependency in my MessageHandler is not resolved (it's null when handling the messages).
If I remove the interception configuration from the Unity container, and simply do this:
IUnityContainer container = new UnityContainer();
container.RegisterType(typeof(IRepository<Person>), typeof(Example.Data.InMemory.Repository<Person>));
It works as expected, and the MessageHandler has an instance if IRepository resolved.