Erw*_*ers 1 c# asp.net-mvc constructor dependency-injection
我有一个控制器,一个DbContext人和一个谁没有.IE中:
public CalendarController()
{
var db = new DbContext();
CalendarController(db); // <= Not allowed
}
public CalendarController(IDbContext db)
{
_calendarManager = new CalendarManager(db);
_userManager = new UserManager(db);
_farmingActionManager = new FarmingActionManager(db);
_cropManager = new CropManager(db);
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,上面给出了错误CalendarController(db):
表达式表示"类型",其中期望"变量","值"或"方法组"
是否可以从另一个构建函数调用?我不想复制所有代码.
你必须像这样链接到构造函数:
public CalendarController() : this(new DbContext())
{
}
Run Code Online (Sandbox Code Playgroud)
这是链接到同一个类中的任何构造函数的语法- 它不必从无参数的一个到参数化的一个,尽管它必须是另一个:)
请注意,这是在构造函数的主体之前,因此您不能先执行任何其他操作,尽管您可以调用静态方法来计算其他构造函数的参数.但是,您不能使用实例方法或属性.所以这没关系:
public Foo() : this(GetDefaultBar())
{
}
public Foo(int bar) { ... }
private static int GetDefaultBar() { ... }
Run Code Online (Sandbox Code Playgroud)
但这不是:
public Foo() : this(GetDefaultBar())
{
}
public Foo(int bar) { ... }
private int GetDefaultBar() { ... }
Run Code Online (Sandbox Code Playgroud)
链接到基类中的构造函数的语法类似:
public Foo() : base(...)
Run Code Online (Sandbox Code Playgroud)
如果您未指定任何一个,: base(...)或者: this(...)编译器隐式: base()为您添加了一个.(这不一定链接到无参数构造函数;它可以有可选参数.)