Autofac属性在基本控制器中注入

时间:2014-11-04 09:42:59

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

我有基础控制器我尝试了属性注入,但没有工作......

public class BaseController : Controller
{
    public ILoggingService loggingService { get; set; }

    public BaseController()
    {

    }
}

这是我的Autofac配置......

var builder = new ContainerBuilder();

// builder.Register(c => new BaseController { loggingService = c.Resolve<ILoggingService>() });
builder.RegisterControllers(Assembly.GetExecutingAssembly())
                   .PropertiesAutowired();

builder.Register(c => new BaseController()).OnActivated(e =>
{
    e.Instance.loggingService = e.Context.Resolve<ILoggingService>();
});
builder.RegisterAssemblyTypes(Assembly.Load("Aizen.Services"))
                   .Where(t => t.Name.EndsWith("Service"))
                   .AsImplementedInterfaces()
                   .InstancePerRequest();

2 个答案:

答案 0 :(得分:0)

您尚未为ILoggingService界面注册具体类型。没有它,Autofac不知道将你的财产设置为实际需要什么。

添加这样的东西(当然替换为真实对象):

builder.RegisterType<YourLoggingServiceGoesHere>().As<ILoggingService>();

答案 1 :(得分:0)

您可以尝试此解决方案:

builder.Register(c => new BaseController {  loggingService = c.Resolve<ILoggingService>() });