Autofac命名注册聚合服务

时间:2018-02-15 23:23:52

标签: dependency-injection aggregate log4net autofac

我试图使用Autofac Aggregate服务重构MVC应用程序中的一些代码。我试图注入的服务之一是使用特定控制器类型的log4net.ILog。的修改 根据建议,我使用模块上的Autofac示例中公开的LoggingModule。离开这个问题,因为它与发布的相同:

var builder = new ContainerBuilder();
builder.RegisterAggregateService<IHomeControllerDependencies>();
//other service registrations
builder.RegisterModule<LoggingModule>();
builder.RegisterType<HomeController>().InstancePerRequest();
builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

接下来,在我的聚合服务中,我使用以下内容(为了简洁而省略其他服务):

public interface IHomeControllerDependencies
{
    ILog Logger { get; }
    //other services
}

public class HomeControllerDependencies : IHomeControllerDependencies
{
    public HomeControllerDependencies(IComponentContext context)
    {
        Logger = context.Resolve<ILog>();
        //other services            
    }

    public ILog Logger { get; }
    //other services
}

然后我在HomeController中注入依赖项对象,如下所示:

public class HomeController : Controller
{    
    private readonly IHomeControllerDependencies _dependencies;

    public HomeController(IHomeControllerDependencies dependencies)
    {
        _dependencies = dependencies;
    }
...
}

我仍然收到'log4net.ILog'尚未注册的错误。 的修改 这里有趣的是,当我在Controller的构造函数中显式使用Logger并将其从聚合服务中取出而不修改注册时,它可以正常工作并获取日志记录实例,甚至可以正确键入HomeController Logger:

public class HomeController : Controller
    {
        public ILog Logger { get; }

        public HomeController(IHomeControllerDependencies dependencies, ILog logger)
        {
            _dependencies = dependencies;
            Logger = logger;
        }
...
}

骨料:

public interface IHomeControllerDependencies
{
    //other services
}

public class HomeControllerDependencies : IHomeControllerDependencies
{
    public HomeControllerDependencies(IComponentContext context)
    {
        //other services            
    }

    //other services
}

我想我可以保持这种方式,但我使用聚合服务的主要原因是有一个参数构造函数。

由于

0 个答案:

没有答案