我使用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...
}
}
這是我的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'公共屬性總是爲空,因此會在運行時中斷。
任何想法可能是我的問題?感謝您的幫助! :)
可能的重複[如何使用AutoFac注入屬性?](http://stackoverflow.com/questions/15600440/how-to-use-property-injection-with-autofac) – Steve
我想你有你的註冊錯誤的方式。控制器需要應用'PropertiesAutowired',而不是依賴項。 – Steve
您需要將您的Test對象傳遞給構造函數,或者不要在構造函數中使用此對象。在執行構造函數之前,不能分配屬性。 – trailmax