c# – 在ASP.NET核心中初始化依赖注入时传递参数
发布时间:2020-12-15 22:33:48 所属栏目:百科 来源:网络整理
导读:我有一个简单的类,看起来像这样: public class TestClass1{ private string testString = "Should be set by DI"; public TestClass1(string testString) { this.testString = testString; } public string GetData() { return testString + DateTime.Now;
我有一个简单的类,看起来像这样:
public class TestClass1 { private string testString = "Should be set by DI"; public TestClass1(string testString) { this.testString = testString; } public string GetData() { return testString + DateTime.Now; } } 我想在一个简单的ASP.NET核心Web应用程序中使用内置DI注入它,但在初始化依赖注入时设置了“testString”参数. 我尝试在startup.cs中设置以下内容,但它在运行时失败,因为TestClass1没有无参数构造函数: services.AddScoped(provider => new TestClass1("Success!")); 解决方法
我怀疑你错过了代码的重要部分,你对DI的使用是完全错误的,而不是注册.
public class MyController { private readonly MyClass myClass; public MyController() { // This doesn't work and do not involve DI at all // It will fail because MyClass has no parameterles constructor this.myClass = new MyClass(); } } 上面的代码不起作用,因为DI不是编译器魔法,可以让你在类型上调用new时神奇地注入依赖项. public class MyController { private readonly MyClass myClass; public MyController(MyClass myClass) { // This should work,because the IoC/DI Container creates the instance // and pass it into the controller this.myClass = myClass; } } 当你使用DI / IoC时,你让构造函数生成并实例化对象,因此你永远不会在服务类中调用new.只需在构造函数中告诉您需要某种类型的实例或它的接口. 编辑: 这曾经在ASP.NET Core的早期版本(beta版)中工作.应该仍然有效,但仅限于参数: public class MyController { public IActionResult Index([FromServices]MyClass myClass) { } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |