0
votes

I am using Windsor Castle. I have a Business class and an Interceptor configured as following:

windsorContainer.Register(Component.For<IMyBusinessInterface>()
    .ImplementedBy<MyBusinessClass>()
    .Interceptors<MyInterceptorAttribute>()
    .LifestyleTransient());

IMyBusinessInterface and MyBusinessClass are inside the project Business. MyInterceptorAttribute is inside the project Interceptors. Business project has a reference to Interceptors project.

MyInterceptorAttribute is used as data annotation on a method of the MyBusinessClass

[MyInterceptorAttribute]
public class MyBusinessClass 
{
    public IUnitOfWork uow { get; set; }
    public MyBusinessClass(IUnitOfWork uow)
    {
        uow = uow;
    }

    [MyInterceptorAttribute]
    public MyReturnValue MyBusinessMethod(MyArguments arguments)
    {
        //...
    }
}

I need to pass (or retrieve) inside the MyInterceptorAttribute class the same instance of the unit of work that has been instanciated inside the container of Windsor Castle.

In this moment I pass two different instances.

I cannot retrieve the instance of unit of work inside the MyInterceptorAttribute because to get the invocation.InvocationTarget I would create a circular reference.

public class MyInterceptorAttribute : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        IMyBusinessInterface obj = invocation.InvocationTarget as MyBusinessClass; //I cannot do this because of circular reference

        //obj.uow = ..

    }
}

So I was thinking to add a public property of unit of work inside the MyInterceptorAttribute and get same instance of unit of work of the business class via dependency injection... something like this:

public class MyInterceptorAttribute : IInterceptor
{
    public IUnitOfWork uow { get; set; }

    public void Intercept(IInvocation invocation)
    {
        //uow...            
    }
}

But in this moment I get two different instances. Is it possible to get the same instance modifying for example the configuration of windsor caste... I suppose using DependsOn or DynamicParameters or something similar?

Thank you

1

1 Answers

0
votes

Instead of implementing your interceptor as an attribute, which is instantiated by the .Net runtime and therefore not available for dependency injection by Windsor, try using the standard [Interceptor(typeof(MyInterceptor))] attribute.

You can then register MyInterceptorin Windsor with whatever lifestyle you wish and dependency injection for the Unit Of Work, or any other dependency, will work as expected.