Autofac Generic Service resolution at runtime

天涯浪子 提交于 2019-12-02 00:05:00

You could isolate that coupling by creating a concrete IHandlerFactory, say AutofacHandlerFactory, which would receive the ILifetimeScope. That coupling seems inevitable since the container is the only one who can resolve the proper IHandler<T>.

Coupling with ILifetimeScope might be a bad idea, but then, the coupling is isolated inside the concrete IHandlerFactory, and the Bus just uses it through an interface. Let's say you change the container and starts using Ninject, you could just implement a NinjectHandlerFactory to do the job.

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>(T message) {
    _OwnScope.Resolve<IHandler<T>>.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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!