Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Autofac不自动将属性关联到自定义类_C#_Asp.net Mvc_Autofac_Asp.net 4.5 - Fatal编程技术网

C# Autofac不自动将属性关联到自定义类

C# Autofac不自动将属性关联到自定义类,c#,asp.net-mvc,autofac,asp.net-4.5,C#,Asp.net Mvc,Autofac,Asp.net 4.5,我正在尝试使用Autofac autowired属性为控制器调用的自定义类设置一个类。我有一个测试项目来显示这一点。我的解决方案中有两个项目。MVC web应用程序和服务类库。代码如下: 在服务项目AccountService.cs中: public interface IAccountService { string DoAThing(); } public class AccountService : IAccountService { public string DoAT

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

在服务项目AccountService.cs中:

public interface IAccountService
{
    string DoAThing();
}

public class AccountService : IAccountService
{
    public string DoAThing()
    {
        return "hello";
    }
}
现在剩下的都在MVCWeb项目中

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));
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();
    }

//...
}

从上面的代码可以看出,
\u accountServiceTest
\u accountService
在控制器中工作正常,但是当在
Test.cs
DoSomething()方法中设置断点时,
\u accountService
始终为空,当您使用
new
autofac创建对象时,无论我在
global.asax.cs
中输入什么,autofac都不知道有关此对象的任何信息。所以在
Test
类中,
IAccountService
的值总是为空是正常的

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

public HomeController(IAccountService accountService,ITest testService)

这是有道理的。我测试了这些变化,它是有效的。我感谢你的帮助!
public HomeController(IAccountService accountService,ITest testService)