简体   繁体   中英

Autofac not auto wiring properties to a custom class

I am trying to setup a class using Autofac autowired properties for a custom class which a controller calls. I have a setup a test project to show this. I have two projects in my solution. An MVC web application and a class library for services. Here's the code:

In the service project, AccountService.cs:

public interface IAccountService
{
    string DoAThing();
}

public class AccountService : IAccountService
{
    public string DoAThing()
    {
        return "hello";
    }
}

Now the rest is in the MVC web project.

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

//...
}

As you can see from the code above, both _accountServiceTest and _accountService work fine in the controller, but when setting a break point in DoSomething() method of the Test.cs , _accountService is always null, no matter what I put in the global.asax.cs .

When you create object with new autofac does not know anything about this object. So it's normal you always get null for IAccountService in Test class.

So proper way to this: Set Interface for Test class and register it. Then add this interface to your HomeController constructor.

public HomeController(IAccountService accountService,ITest testService)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM