2016-02-05 96 views
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始終爲空,無論我放在中。

回答

2

當您使用new創建對象時,autofac不知道任何有關此對象的信息。所以這是正常的,你得到空始終爲IAccountService

如此正確的方法: 爲Test類設置接口並註冊它。然後將此接口添加到您的HomeController構造函數。

public HomeController(IAccountService accountService,ITest testService) 
+0

這很有道理。我測試了這些變化,併發揮了作用。我很感激幫助! –