属性 构造函数中注入的值为空

Property injected value is null in constructor

我正在使用 OWIN 中间件在我的 ASP.NET MVC 5 Web 应用程序中连接 Autofac 依赖项注入(因此使用 startup.cs 而不是 global.asax),并尝试使用 属性 注入以在 Controller 中设置 public 变量。

我正在尝试使用 属性 注入让 Autofac 在 LoginController 中自动设置测试 属性。

public interface ITest
{
    string TestMethod();
}

public class Test : ITest
{
    public string TestMethod()
    {
        return "Hello world!";
    }
}

public class LoginController : Controller
{
    public ITest Test { get; set; }

    public LoginController()
    {
        var aaa = Test.TestMethod();

        // Do other stuff...
    }
}

这是我的 startup.cs 的样子。我一直在玩,所以可能不需要其中的一些代码(或导致我的问题?)。

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var builder = new ContainerBuilder();
        builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
        builder.RegisterType<Test>().As<ITest>().SingleInstance();
        builder.Register(c => new Test()).As<ITest>().InstancePerDependency();

        builder.RegisterType<ITest>().PropertiesAutowired();
        builder.RegisterType<LoginController>().PropertiesAutowired();

        builder.RegisterModelBinderProvider();
        builder.RegisterFilterProvider();

        var container = builder.Build();

        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

        app.UseAutofacMiddleware(container);

        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);

        // Some other stuff...
    }
}

因此,'Test' public 属性 始终为空,因此会在运行时中断。

有什么想法可能是我的问题吗?提前感谢您的帮助! :)

So, the 'Test' public property is always null, and therefore breaks on runtime.

它并不总是空的。它在构造函数中为空,因为 Autofac(实际上是所有代码)在构造函数 finished.

之前无法设置属性
public class LoginController : Controller
{
    public ITest Test { get; set; }

    public LoginController()
    {
        // Test is null, will always be null here
        var aaa = Test.TestMethod();
    }
}

autofac 的超级虚拟版本会做类似的事情:

var controller = new LoginController();
controller.Test = new Test();

如果你需要在 属性 设置后执行代码,你可以像下面这样做一些骇人听闻的事情(但实际上你应该只使用构造函数注入):

public class LoginController : Controller
{
    private ITest _test;
    public ITest Test 
    { 
      get { return _test; }
      set 
      {
        var initialize = (_test == null);
        _test = value;
        if (initialize)
        {
          Initialize();
        }
      }
    }

    public LoginController()
    {
    }

    private void Initialize()
    {
      var aaa = Test.TestMethod();
    }
}

同样,更合乎逻辑的方法是:

public class LoginController : Controller
{
    private readonly ITest _test;

    public LoginController(ITest test)
    {
        _test = test;
        var aaa = _test.TestMethod();

        // Do other stuff...
    }
}