繁体   English   中英

Autofac 不会自动将属性连接到自定义类

[英]Autofac not auto wiring properties to a custom class

我正在尝试使用 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));

测试.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 = "";
    }
}

家庭控制器.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在控制器中都_accountServiceTest _accountService工作,但是在Test.cs DoSomething()方法中设置Test.cs_accountService始终为空,无论我在global.asax.cs放置什么global.asax.cs .

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

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

public HomeController(IAccountService accountService,ITest testService)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM