【问题标题】:Autofac not auto wiring properties to a custom classAutofac 不会自动将属性连接到自定义类
【发布时间】:2016-02-05 14:49:31
【问题描述】:

我正在尝试使用 Autofac 自动装配属性为控制器调用的自定义类设置一个类。我有一个设置一个测试项目来展示这一点。我的解决方案中有两个项目。一个 MVC Web 应用程序和一个服务类库。代码如下:

在服务项目中,AccountService.cs:

public interface IAccountService
{
    string DoAThing();
}

public class AccountService : IAccountService
{
    public string DoAThing()
    {
        return "hello";
    }
}

现在剩下的都在 MVC Web 项目中了。

Global.asax.cs

var builder = new ContainerBuilder();

builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();

builder.RegisterAssemblyTypes(typeof(AccountService).Assembly)
   .Where(t => t.Name.EndsWith("Service"))
   .AsImplementedInterfaces().InstancePerRequest();

builder.RegisterType<Test>().PropertiesAutowired();

builder.RegisterFilterProvider();

var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

Test.cs:

public class Test
{
    //this is null when the var x = "" breakpoint is hit.
    public IAccountService _accountService { get; set; }

    public Test()
    {

    }

    public void DoSomething()
    {
        var x = "";
    }
}

HomeController.cs

public class HomeController : Controller
{
    //this works fine
    public IAccountService _accountServiceTest { get; set; }
    //this also works fine
    public IAccountService _accountService { get; set; }

    public HomeController(IAccountService accountService)
    {
        _accountService = accountService;
    }
    public ActionResult Index()
    {
        var t = new Test();
        t.DoSomething();
        return View();
    }

//...
}

从上面的代码可以看出,_accountServiceTest_accountService 在控制器中都可以正常工作,但是在Test.csDoSomething() 方法中设置断点时,_accountService 始终为空,不管我在global.asax.cs 里放了什么。

【问题讨论】:

    标签: c# asp.net-mvc autofac asp.net-4.5


    【解决方案1】:

    当您使用new 创建对象时,autofac 对此对象一无所知。因此,在 Test 类中,IAccountService 总是为 null 是很正常的。

    正确的方法是: 为测试类设置接口并注册它。然后将此接口添加到您的 HomeController 构造函数中。

    public HomeController(IAccountService accountService,ITest testService)
    

    【讨论】:

    • 这是有道理的。我测试了更改并且它有效。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 2017-11-05
    • 1970-01-01
    相关资源
    最近更新 更多