Ctrl_Alt_Defeat
Ctrl_Alt_Defeat

Reputation: 4009

Initialize class as part of DI

I am writing a new ASP.NET Core Application and I am using the inbuilt DI Framework.

I have a service that I need to run an Initaliaze method as part of the DI - is this possible with the in built Framework DI?

I have done something like this before with Simple Injector using the following code:

container.RegisterInitializer<MyService>(instance =>
{
    instance.Initialize("Parameter to Initialize method");
});

I am registering most of my service in the .NET Core as below:

public static void RegisterServiceDependencies(this IServiceCollection services)
{
    services.AddTransient<IServiceA, ServiceA>();
    services.AddTransient<IServiceB, ServiceB>();
    //etc etc

However looking at the services intellisense I don't see anything like RegisterInitializer.

Upvotes: 0

Views: 960

Answers (1)

hugo
hugo

Reputation: 1859

Something like this?

public static void RegisterServiceDependencies(this IServiceCollection services)
{
            services.AddTransient(sp =>
            {
                var instance = sp.GetService<MyClass>(); /* depends on your type */

                instance.Initialize("Parameter to Initialize method");
                return instance;
            });
});

Upvotes: 1

Related Questions