2016-02-05 46 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

这很有道理。我测试了这些变化,并发挥了作用。我很感激帮助! –