.net - "Reverse-Resolution"带有 Ioc 容器?

标签 .net dependency-injection ioc-container

我想要注册一个类并让 IOC 容器隐式注册与该类关联的接口(interface),而不是注册接口(interface)到类的绑定(bind)。我想知道是否有任何 IOC 容器可以做到这一点,尽管我特别需要 Unity 的答案。

为了明确我的目的,请注意:

public interface IFred
{
    int Go();
}
public class Fred : IFred
{
    public int Go()
    {
        return 1;
    }
}

class Program
{
    static void Main(string[] args)
    {
        UnityContainer container = new UnityContainer();

        container.RegisterType<Fred>();     //contra-variant registration?
        IFred foo = container.Resolve<IFred>();  //variant resolution?
    }
}

在上面的示例中,我希望返回一个“Fred”实例,即使我没有显式注册 IFred 映射。

最佳答案

我认识一对夫妇(虽然很抱歉,但不是Unity)

Autofac:

ContainerBuilder builder = new ContainerBuilder();
builder
    .RegisterType<Fred>()
    .AsImplementedInterfaces();

和温莎城堡:

WindsorContainer container = new WindsorContainer();
container.Register(
    Classes
        .From(typeof(Fred))
        .Pick()
        .LifestyleTransient()
        .WithServiceAllInterfaces());

关于.net - "Reverse-Resolution"带有 Ioc 容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19601295/

相关文章:

.net - 如何在不使用服务定位器模式的情况下使用具有依赖注入(inject)的工厂

c# - 如何为 Unity 中的所有注册类型配置日志拦截器?

c# - 在 C# 控制台应用程序中设置结构图

c# - 使用什么是组合 Autofac 和 Dapper 的首选方式

.net - 大型图像调整大小库

c# - 在日期时间范围内使用 ContentSearch-API 查询 Sitecore Lucene-index

java - 无法在 Servlet 筛选器中 Autowiring 具有请求范围的组件

缺少 .NET 核心 2.1 模板

c# - 使用 Json.NET 的自定义反序列化

Java 构造函数注入(inject)