在类中注入一个通用服务,它正在MVC 5中注入

时间:2016-04-21 15:58:09

标签: c# asp.net-mvc dependency-injection autofac

我有一个ILogger接口和一个ILogger<T>,它是实际实现并继承自前者的接口。我在ILogger<T>注册了Autofac界面,但它运行正常,但我必须要求ILogger<T>。有可能在以下情况下做到:

class MyService
{
    public MyService(ILogger logger)...
}

logger实际上是ILogger<MyService>

1 个答案:

答案 0 :(得分:0)

首先注册:来自docs

builder.RegisterGeneric(typeof(NHibernateRepository<>))
   .As(typeof(IRepository<>))
   .InstancePerLifetimeScope();

所以你的代码

builder.RegisterGeneric(typeof(LoggerService<>))
   .As(typeof(ILogger<>))
   .InstancePerLifetimeScope();

这是我的工作样本:

using System;
using Autofac;          

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");

        var builder = new ContainerBuilder();

        builder.RegisterGeneric(typeof(LoggerService<>))
               .As(typeof(ILogger<>))
               .InstancePerLifetimeScope();

        var container = builder.Build();

        var obj = container.Resolve<ILogger<MyService>>();
        var obj2 = container.Resolve<ILogger<OtherService>>();

        Console.WriteLine(obj.Log());
        Console.WriteLine(obj2.Log());
    }
}

public interface ILogger<T>
{
    string Log();
}

public class LoggerService<T> : ILogger<T>
{
    public string Log()
    {
        return typeof(T).Name;
    }
}

public class MyService
{

}

public class OtherService
{

}

输出:

  

Hello World

     

为MyService

     

OtherService