Autofac无法自动将属性连接到自定义类

问题描述 投票:2回答:1

我正在尝试使用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在控制器中都可以正常工作,但是在DoSomething()Test.cs方法中设置断点时,_accountService始终为null,否不管我在global.asax.cs中输入什么。

c# asp.net-mvc autofac asp.net-4.5
1个回答
3
投票

使用new创建对象时,autofac对该对象一无所知。因此,通常在IAccountService类中对于Test总是为null。

这样的正确方法:设置Test类的接口并注册。然后将此接口添加到您的HomeController构造函数。

public HomeController(IAccountService accountService,ITest testService)
© www.soinside.com 2019 - 2024. All rights reserved.