Autofac Generic Service resolution at runtime

后端 未结 2 419
不知归路
不知归路 2021-01-22 21:10

Recently, Castle added support for interface factories with implementations provided by the kernel. I am wondering if there is a way to do this in autofac also. I have read abou

2条回答
  •  自闭症患者
    2021-01-22 21:39

    Seems like the answer is 'No'.

    I've tried to use AggregateService which is supposed to do what you want, but it crashes during factory resolution with message 'The type "Castle.Proxies.IComponentFactoryProxy" from assembly "DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" has tried to implement an unaccessible interface.' (The original message is in Russian, I've translated it).

    I can't figure out another approach that would work without a manual (yet quite simple) implementation. Maybe you should write to Nicholas Blumhardt.

    In fact, I'd better do it this way:

    public class Bus {
      readonly ILifetimeScope _OwnScope;
    
      // Autofac always provides ILifetimeScope that owns a component as a service to the component
      // so it can be used as a dependency
      public Bus(ILifetimeScope ownScope) {
        _OwnScope = ownScope;
      }
    
      void Send(T message) {
        _OwnScope.Resolve>.Handle(message);
      }
    }
    

    You will probably argue that coupling with ILifetimeScope is a bad idea. Well, it's quite a simple interface which might be wrapped into your own implementation. Or you may factor the code out into a simple factory class. Well, it seems like you know how to do this without my suggestions.

提交回复
热议问题