我已经阅读了有关这方面的一些文章,现在让Autofac使用MVC6的预览版本并向我的控制器注入一个服务! Yaaay!
然而,我还在服务中添加了一个注入(这是一个nuget类库),所有注册都在StartUp.cs中按照建议注册。它只是不起作用!
与将服务注入控制器的代码完全相同,但不工作,它按预期注入服务,但是在服务中调用注入的repo的下一行只会获得对象引用错误。
"dependencies": {
"Microsoft.CSharp": "4.0.0-beta-23019",
"Autofac": "4.0.0-beta6-110",
"Autofac.Framework.DependencyInjection": "4.0.0-beta6-110",
"Microsoft.Framework.DependencyInjection.Abstractions": "1.0.0-beta6",
"SceneStealer.Services.Interfaces": { },
"SceneStealer.Models": { },
"SceneStealer.Data": { },
"SceneStealer.Data.Interfaces": { },
"System.Collections": "4.0.10-beta-23019",
"System.Linq": "4.0.0-beta-23019",
"System.Runtime": "4.0.10-beta-23019",
"System.Threading": "4.0.10-beta-23019"
},
public class AutofacModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder
.Register(c => new ConferenceService())
.As<IConferenceService>()
.InstancePerLifetimeScope();
builder.Register(c => new ConferenceRepo())
.As<IConferenceRepo>()
.InstancePerLifetimeScope();
}
}
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add Application Insights data collection services to the services container.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
// Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers.
// You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json.
// services.AddWebApiConventions();#services
//Autofac config
services.AddMvc();
// Create the Autofac container builder.
var builder = new ContainerBuilder();
// Add any Autofac modules or registrations.
builder.RegisterModule(new AutofacModule());
// Populate the services.
builder.Populate(services);
// Build the container.
var container = builder.Build();
// Resolve and return the service provider.
return container.Resolve<IServiceProvider>();
}