gpt4 book ai didi

c# - Autofac 不会自动将属性连接到自定义类

转载 作者:行者123 更新时间:2023-11-30 23:29:49 24 4
gpt4 key购买 nike

我正在尝试使用 Autofac Autowiring 属性为 Controller 调用的自定义类设置一个类。我有一个测试项目来展示这个。我的解决方案中有两个项目。一个 MVC Web 应用程序和一个服务类库。这是代码:

在服务项目中,AccountService.cs:

public interface IAccountService
{
string DoAThing();
}

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

现在剩下的是在 MVC web 项目中。

全局.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));

测试.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在 Controller 中工作正常,但在 DoSomething() 中设置断点时Test.cs 的方法, _accountService始终为空,无论我在 global.asax.cs 中放入什么.

最佳答案

当你用 new 创建对象时,autofac 不知道这个对象的任何信息。所以对于 Test 类中的 IAccountService 总是得到 null 是正常的。

正确的做法是:为测试类设置接口(interface)并注册它。然后将此接口(interface)添加到您的 HomeController 构造函数中。

public HomeController(IAccountService accountService,ITest testService)

关于c# - Autofac 不会自动将属性连接到自定义类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35226961/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com