How to use Autofac to inject specific implementation in constructor

后端 未结 1 505
北恋
北恋 2021-01-12 07:22

I have two classes that take a ILastActivityUpdator as a constructor parameter: UserService and AnonymousUserService.



        
相关标签:
1条回答
  • 2021-01-12 07:35

    Autofac is nicely documented and it looks like you can find what you are after here. From what I can tell, if you have registered your updators with

    builder.RegisterType<LastActivityUpdator>();
    builder.RegisterType<AnonymousUserLastActivityUpdator>();
    

    then you should be able to register your services with

    builder.Register(c => new UserService(c.Resolve<LastActivityUpdator>()));
    builder.Register(c => new AnonymousUserService(c.Resolve<AnonymousUserLastActivityUpdator>()));
    

    or

    builder.RegisterType<UserService>().WithParameter(
        (p, c) => p.ParameterType == typeof(ILastActivityUpdator),
        (p, c) => c.Resolve<LastActivityUpdator>());
    
    builder.RegisterType<AnonymousUserService>().WithParameter(
        (p, c) => p.ParameterType == typeof(ILastActivityUpdator),
        (p, c) => c.Resolve<AnonymousUserLastActivityUpdator>());
    

    Then when you resolve UserService or AnonymousUserService from the container, they will get the correct dependencies.

    As an aside, if an interface is injected into a class, then that class should function correctly with all implementations of that interface (LSP). From the class names, it looks like AnonymousUserService only works with AnonymousUserLastActivityUpdator and not any implementation of ILastActivityUpdator. If that is the case, then it might be appropriate to introduce a different abstraction (like IAnonymousUserLastActivityUpdator) as you suggested.

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