2
我正在嘗試使用Autofac autowired屬性爲控制器調用的自定義類設置類。我有一個設置測試項目來展示這一點。我的解決方案中有兩個項目。 MVC Web應用程序和服務類庫。下面的代碼:Autofac不自動將屬性自動接線到自定義類
在服務項目中,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
始終爲空,無論我放在中。
這很有道理。我測試了這些變化,併發揮了作用。我很感激幫助! –