运行时的Autofac通用服务解析 [英] Autofac Generic Service resolution at runtime

查看:77
本文介绍了运行时的Autofac通用服务解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,Castle通过内核提供的实现添加了对接口工厂的支持.我想知道是否也有办法在autofac中做到这一点.我已经阅读了有关委托工厂的信息,但我认为我可能会缺少一些东西,无法使它正常工作.这就是我的想法:

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 about the delegate factories, but I think I might be missing something, and am unable to get it to work. Here is what I am thinking:

class Message { }

interface IHandle<T> {
    void Handle(T message);
}

class Handle<Message> : IHandle<Message> {
    ...
}

class Bus {
    .ctor (? lookup) {
        _lookup = lookup;
    }

    void Send<T>(T message) {
        _lookup.GetHandler<T>().Handle(message);
    }
}

var builder = new ContainerBuilder();
builder.RegisterType<Handle<Message>>().As<IHandle<Message>>();
builder.RegisterType<Bus>();

var container = builder.Build();
container.Resolve<Bus>().Send<Message>(new Message());

我想做的是将容器保持在总线之外(因为我同意服务定位器是一种反模式)或任何其他实现.如果我只是将容器提供给总线,或者创建一些包装容器的类工厂,那么这个问题就很容易了.只是要确保没有办法做到这一点.

What I'm trying to do is keep the container out of the bus (as I agree that service locator is an anti-pattern) or any other implementation. This problem is easy if I just feed the container to the bus, or create some class factory that wraps the container. Just trying to make sure there isn't a way to do this already.

顺便说一句,iirc的城堡方式使我可以注册这样的东西:

Btw, the castle way iirc allows me to register something like this:

interface IHandlerFactory {
    IHandle<T> GetHandler<T>();
}

container.Register<IHandlerFactory>().AsFactory();

谢谢, 尼克

推荐答案

您可以通过创建一个具体的IHandlerFactory(例如AutofacHandlerFactory)来隔离该耦合,该对象将接收ILifetimeScope.这种耦合似乎是不可避免的,因为容器是唯一可以解析正确的IHandler<T>的容器.

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>.

ILifetimeScope耦合可能不是一个好主意,但是,此耦合在具体的IHandlerFactory内部是隔离的,而Bus只是通过接口使用它.假设您更改了容器并开始使用Ninject,则只需实现NinjectHandlerFactory即可完成工作.

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.

这篇关于运行时的Autofac通用服务解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆