简体   繁体   English

在startup.cs in.Net Core中实例化一个class object

[英]Instantiate a class object in startup.cs in .Net Core

I am trying to pass an interface and settings into a class while creating an instance of that class in startup.cs in.Net Core Project.我正在尝试将接口和设置传递给 class,同时在.Net Core 项目中的 startup.cs 中创建该 class 的实例。 I am using the below code to do so.我正在使用下面的代码来做到这一点。 I have some code written in the constructor of Student class but while starting the application the Code/Logic inside the constructor is not working.我在 Student class 的构造函数中编写了一些代码,但是在启动应用程序时,构造函数中的代码/逻辑不起作用。 There is no error but the debug pointer is not hitting the constructor of Student class.没有错误,但调试指针未命中 Student class 的构造函数。

services.AddSingleton(c => new Student(settings, resourceSetting, c.GetService<IPersonService>()));

If I am using the below code then the code inside Student constructor is working fine.如果我使用下面的代码,那么 Student 构造函数中的代码工作正常。

 Student studentHandler = new Student(settings, resourceSetting,);
 services.AddSingleton<Student>(studentHandler);

But I need to pass Service interface in the constructor to do some work while starting the Project.但是我需要在构造函数中传递服务接口才能在启动项目时做一些工作。 Can anyone help me with what I am missing here?谁能帮我解决我在这里缺少的东西?

the debug pointer is not hitting the constructor of Student class调试指针未命中 Student class 的构造函数

That's because you're registering the type as an implementation factory in the first snippet, using AddSingleton<TService> (this IServiceCollection services, Func<IServiceProvider,TService> implementationFactory) With this method, the implementation factory delegate (and subsequently the Student constructor) won't be called until the dependency is resolved .这是因为您在第一个片段中将类型注册为实现工厂,使用AddSingleton<TService> (this IServiceCollection services, Func<IServiceProvider,TService> implementationFactory)使用此方法,实现工厂委托(以及随后的Student构造函数)在依赖解决之前不会被调用。

In the second snippet, you're directly instantiating the type at service registration and adding that instance to the service collection with AddSingleton<TService> (this IServiceCollection services, TService implementationInstance) .在第二个片段中,您在服务注册时直接实例化类型,并使用AddSingleton<TService> (this IServiceCollection services, TService implementationInstance)将该实例添加到服务集合中。


Here's an example with logs explaining each step in each approach:这是一个示例,其中的日志解释了每种方法中的每个步骤:

class Program
{
    static void Main(string[] args)

    {
        RegisterImplementationFactory();
        RegisterImplementation();
    }

    static void RegisterImplementationFactory()
    {
        Console.WriteLine("RegisterImplementationFactory ------------");

        var services = new ServiceCollection();

        Console.WriteLine("Registering Student...");
        services.AddSingleton(c => new Student());
        Console.WriteLine("Student registered.");

        Console.WriteLine("Building ServiceProvider...");
        var serviceProvider = services.BuildServiceProvider();
        Console.WriteLine("ServiceProvider built.");

        Console.WriteLine("Resolving Student...");
        Student student = serviceProvider.GetService<Student>();
        Console.WriteLine("Student resolved.");

        Console.WriteLine("RegisterImplementationFactory ------------");
        Console.WriteLine();
    }

    static void RegisterImplementation()
    {
        Console.WriteLine("RegisterImplementation ------------");

        var services = new ServiceCollection();

        Console.WriteLine("Registering Student...");
        Student studentToRegister = new Student();
        services.AddSingleton(studentToRegister);
        Console.WriteLine("Student registered.");

        Console.WriteLine("Building ServiceProvider...");
        var serviceProvider = services.BuildServiceProvider();
        Console.WriteLine("ServiceProvider built.");

        Console.WriteLine("Resolving Student...");
        Student student = serviceProvider.GetService<Student>();
        Console.WriteLine("Student resolved.");

        Console.WriteLine("RegisterImplementation ------------");
        Console.WriteLine();
    }
}

class Student
{
    public Student()
    {
        Console.WriteLine("!!! Instantiating Student...");
    }
}

The output of this is: output 是:

RegisterImplementationFactory ------------
Registering Student...
Student registered.
Building ServiceProvider...
ServiceProvider built.
Resolving Student...
!!! Instantiating Student...
Student resolved.
RegisterImplementationFactory ------------

RegisterImplementation ------------
Registering Student...
!!! Instantiating Student...
Student registered.
Building ServiceProvider...
ServiceProvider built.
Resolving Student...
Student resolved.
RegisterImplementation ------------

With this you can clearly see that when registering using the factory delegate, the Student constructor isn't called until the type is resolved (with GetService<Student>() in this case).有了这个,您可以清楚地看到,在使用工厂委托进行注册时,在解析类型之前不会调用Student构造函数(在这种情况下使用GetService<Student>() )。

It seems you are using Dependency Injection, so I would recommend based on your constructor to further make use of the DI engine.您似乎正在使用依赖注入,因此我建议您根据您的构造函数进一步利用 DI 引擎。

First, you will want to register the settings and resourceSetting objects首先,您需要注册settingsresourceSetting对象

services.AddSingleton<Student>(settings);
services.AddSingleton<Student>(resourceSetting);

Then register your Student class as well然后也注册您的Student class

services.AddSingleton<Student>();

And now once you build your ServiceCollection into the ServiceProvider via .BuildServiceProvider();现在,一旦您通过.BuildServiceProvider();ServiceCollection构建到ServiceProvider中; (If you are doing a console app) you can call: (如果你正在做一个控制台应用程序)你可以调用:

var myStudent = myServiceProvider.GetRequiredService<Student>();

If you are doing this in something like asp.net, then you would simply just inject your Student class into a controller or other such service for consumption如果您在 asp.net 之类的东西中执行此操作,那么您只需将您的Student class 注入 controller 或其他此类服务以供消费

class MyController : ControllerBase
{

    private Student Student { get; }

    public MyController(Student student)
    {
       Student = student ?? throw new ArgumentNullException(nameof(student));
    }
 
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Startup.cs 中实例化 singleton class 然后在网络核心中使用? - how to instantiate a singleton class in Startup.cs and then use in net core? 如何在Startup.cs中实例化此对象 - how to instantiate this object in Startup.cs .net 核心 Startup.cs CreateScope 或 BuildServiceProvider - .net core Startup.cs CreateScope or BuildServiceProvider .NET Core program.cs 和 Startup.cs 未命中 - .NET Core program.cs and Startup.cs not hit 如何修复 .NET Core 中 Startup.cs 类中的依赖注入错误 - How to fix the Dependency Injection error in Startup.cs class in .NET Core 如何在测试中从 ConfigureServices 将设置传递到 class(派生 ASP.NET Core Startup.cs) - How to pass in settings into a class (derived ASP.NET Core Startup.cs) from ConfigureServices in a test .NET Core 2中Startup.cs中的“默认情况下如何向DI注册IConfiguration对象” - How can “IConfiguration object is registered with DI by default” in Startup.cs in .NET Core 2 在ASP.NET CORE中的Startup.cs中设置动态变量 - Set Dynamic Variables in Startup.cs in ASP.NET CORE 在Startup.cs .net core 2.1中加载程序集 - Load assembly in Startup.cs .net core 2.1 如何在 ASP.NET Core 中的 Startup.cs 中注册 RoleManager - How to register RoleManager in Startup.cs in ASP.NET Core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM