【发布时间】:2017-10-13 01:29:34
【问题描述】:
我有一个实例,当我使用Autofac 时,我的控制器从未实例化。我想我在配置上做错了什么,但我无法弄清楚。我的解决方案中有 2 个项目。 1) API 2) 核心 所有模型、存储库和服务都存在于核心中。 API 中只有控制器。
如果我导航到默认或值控制器,它们可以正常工作。如果我从MemberController 中删除构造函数,它会起作用,但我会在服务上获得NULL 引用。如果我重新添加构造函数,则永远不会加载 MemberController(构造函数和 get 方法中的断点)。
服务需要实例化数据模型。在下面的实例中,MemberController 将MemberService<MemberDM> 用作IService<IDataModel>。
我相信我已经在我的AutofacModule 中注册了所有内容,但它似乎不起作用,因为构造函数从未在MemberController 中命中。
任何想法/帮助将不胜感激。
Startup.cs
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IContainer ApplicationContainer { get; private set; }
public IConfigurationRoot Configuration { get; private set; }
// This method gets called by the runtime. Use this method to add services to the container.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add service and create Policy with options
services.AddCors(o => o.AddPolicy("CorsPolicy", p =>
{
p.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}));
// Add framework services.
services.AddMvc();
var builder = new ContainerBuilder();
var connectionString = Configuration.GetValue<string>("DBConnection:ConnectionString");
builder.RegisterModule(new AutofacModule(connectionString));
builder.Populate(services);
ApplicationContainer = builder.Build();
return new AutofacServiceProvider(ApplicationContainer);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseCors("CorsPolicy");
app.UseMvc();
appLifetime.ApplicationStopped.Register(() => this.ApplicationContainer.Dispose());
}
}
Autofac 模块
public class AutofacModule :Autofac.Module
{
private string _connectionString;
public AutofacModule(string connectionString)
{
_connectionString = connectionString;
}
protected override void Load(ContainerBuilder builder)
{
// Register Connection class and expose IConnection
// by passing in the Database connection information
builder.RegisterType<Connection>() // concrete type
.As<IConnection>() // abstraction
.WithParameter("connectionString", _connectionString)
.InstancePerLifetimeScope();
// Register Repository class and expose IRepository
builder.RegisterType<Repository>() // concrete type
.As<IRepository>() // abstraction
.InstancePerLifetimeScope();
// Register DataModel as IDataModel
builder.RegisterAssemblyTypes(typeof(IServiceAssembly).GetTypeInfo().Assembly)
.Where(t => t.Name.EndsWith("DM"))
//.AsImplementedInterfaces();
.As<IDataModel>();
// Register Service Class as IService
builder.RegisterAssemblyTypes(typeof(IServiceAssembly).GetTypeInfo().Assembly)
.Where(t => t.Name.EndsWith("Service"))
.Except<IService<IDataModel>>()
//.AsImplementedInterfaces();
.As<IService<IDataModel>>();
}
}
IServiceAssembly
public interface IServiceAssembly
{
}
会员控制器
[Route("api/[controller]")]
public class MemberController : Controller
{
private readonly IService<MemberDM> _memberService;
public MemberController(IService<MemberDM> service)
{
_memberService = service;
}
// GET: api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public async Task<IActionResult> Get(int id)
{
var result = await _memberService.Get(id);
return View(result);
}}
【问题讨论】:
-
不会是因为
.Except<IService<IDataModel>>()的来电吧?如果您的MemberDM实现了IDataModel接口,那么就我所见,它不会被注册 -
我尝试删除它,但它仍然不起作用。
-
您的服务是通用的吗?泛型的
.Name返回TypeName`n,其中n是泛型参数的数量。即MyService<MemberDM>将返回MyService`1作为名称,而不是MyService
标签: c# dependency-injection asp.net-core autofac