小编Dan*_*adt的帖子

属性注入值在构造函数中为null

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

我正在玩属性注入,让Autofac自动在LoginController中设置Test属性.

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...
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的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 …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection autofac property-injection

2
推荐指数
1
解决办法
1303
查看次数