Autofac passing parameter to nested types

后端 未结 1 1878
-上瘾入骨i
-上瘾入骨i 2021-01-05 04:03

I am using Autofac as my IoC in my WCF service. I have a situation where I want to pass an object to a nested type (ie a type that is not resolved directly, but when resolvi

1条回答
  •  萌比男神i
    2021-01-05 04:34

    IMHO, I think you're violating one of the principles of IOC in that a component should not need to know about the dependencies of it's dependencies. In your case, the container doesn't know that SomeBusinessObject has a dependency on User.

    That being said, you may be able to leverage Autofac's Delegate Factories. You could manually register a Func to hide the dependency chain details from the client code:

    var builder = new ContainerBuilder();
    builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>));
    builder.RegisterGeneric(typeof(EventLogger<>)).As(typeof(IEventLogger<>));
    builder.RegisterType();
    
    builder.Register>(c => {
        // Autofac should be able to resolve these Func<> automatically:
        var loggerFactory = c.Resolve>>();
        var sboFactory = c.Resolve, SomeBusinessObject>>();
    
            // Now we can chain the Funcs:
        return u => sboFactory(loggerFactory(u));
    });
    

    Now in your client code, you can do:

    var currentUser = GetUserFromServiceContext();  
    var sboFactory = lifetimeScope.Resolve>();
    var bo = sboFactory(currentUser);
    

    As an aside, I think the lamba/Func support is what makes Autofac the best IOC container. You can do some crazy powerful things if you know how to compose Funcs.

    0 讨论(0)
提交回复
热议问题