Search code examples
c#aoplinfu

Creating LinFu interceptors for all types within an assembly


I'm trying to create LinFu interceptors for all methods in my DAL assembly. While I can do something like this:

[Intercepts(typeof(IFirstRepository))]
[Intercepts(typeof(ISecondaryRepository))]
[Intercepts(typeof(IIAnotherRepository))]
public class DalInterceptor : IInterceptor, IInitialize
{
... 
}

that's getting quite messy and needs manual updating every time a new repository is added to the assembly.

Is there a way to automatically create a proxy class for each type in the assembly?

UPDATE:

I've updated my proxy builder using the suggestion from the author himself (Mr Laureano) so I now have this:

Func<IServiceRequestResult, object> createProxy = request =>
{
    var proxyFactory = new ProxyFactory();
    DalInterceptor dalInterceptor = new DalLiteInterceptor();
    return proxyFactory.CreateProxy<object>(dalInterceptor);
};

The interceptor is set up as before. The issue I'm having now is that the proxy object doesn't include the constructors and methods of the original object (I'm guessing as I'm using object in the generic create method).

Do I just cast this back to the required type or am I doing something fundamentally wrong?

Thanks.


Solution

  • It looks like you're trying to use LinFu's IOC container to intercept various services that are instantiated by the container. It turns out that LinFu has an internal class called ProxyInjector that lets you decide which services should be intercepted and how the proxy for each service instance should be created. Here's the sample code:

    Func<IServiceRequestResult, bool> shouldInterceptServiceInstance = request=>request.ServiceType.Name.EndsWith("Repository");
    
    Func<IServiceRequestResult, object> createProxy = request =>
    {
       // TODO: create your proxy instance here
       return yourProxy;
    };
    
    // Create the injector and attach it to the container so that you can selectively
    // decide which instances should be proxied
    var container = new ServiceContainer();
    var injector = new ProxyInjector(shouldInterceptServiceInstance, createProxy);
    container.PostProcessors.Add(injector);
    
    // ...Do something with the container here
    

    EDIT: I just modified the ProxyInjector class so that it is now a public class instead of an internal class in LinFu. Try it out and let me know if that helps.