【发布时间】:2016-07-03 23:21:44
【问题描述】:
在 ASP.NET Core 1.0 项目中,如何使用 DI 将参数传递给构造函数。例如,如何在 Startup.cs 中注册以下服务。 services.AddTransient(typeof(IStateService), new StateService()); 不起作用,因为 StateService() 需要 BlogingContext 类型的输入参数。或者,是否有替代方法来构建涉及数据库的以下服务?这里State 是一个来自 SQL Server Db 的表。应用程序正在使用 EntityFrameworkCore 和 Code First 方法。我正在使用 2016 年 6 月 27 日发布的 ASP.NET Core 1.0 和 VS2015-Update 3 的最新版本
我看到了一个similar example here,但输入参数的类型并不完全相同。
服务:
public interface IStateService
{
IEnumerable<State> List();
}
public class StateService : IStateService
{
private BloggingContext _context;
public StateService(BloggingContext context)
{
_context = context;
}
public IEnumerable<State> List()
{
return _context.States.ToList();
}
}
【问题讨论】:
-
你有没有试过在启动时用
services.AddDbContext<BloggingContext>();之类的东西注册BloggingContext? docs.asp.net/en/latest/fundamentals/… -
@mollwe 感谢您的帮助。您的代码不会注册我的自定义服务,即
StateService -
如果您将状态服务注册为
service.AddTransient<IStateService, StateService>();,那会成功吗? -
@mollwe 但是 StateService() 构造函数需要一个 BloggingContext 类型的参数。这就是 VS 所抱怨的。
-
如果向下滚动一点,就会有一个带有 ICharacterRepository 和 ApplicationDbContext 的 CharacterController。再往下,他们将它们注册为 DI。 ICharacterRepository 匹配您的 IStateService 并且 ApplicationDbContext 匹配您的 BloggingContext...
标签: c# asp.net-core visual-studio-2015 dependency-injection entity-framework-core