C# Autofac不自动将属性关联到自定义类
我正在尝试使用Autofac autowired属性为控制器调用的自定义类设置一个类。我有一个测试项目来显示这一点。我的解决方案中有两个项目。MVC web应用程序和服务类库。代码如下: 在服务项目AccountService.cs中: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
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)