0

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.

3
  • It is possible using a factory delegate as one suggested in an answer but there may be some little caveats to watch out for. Commented Jan 22, 2019 at 11:45
  • 1
    Sad to see you leave :'(. There is so much Simple Injector can do for you which the built-in container just can't and will never do. Commented Jan 22, 2019 at 16:54
  • @Steven - agreed - this was an decision made above my head - however for an upgrade to another huge .NET Framework project we are ripping out Spring.NET and I have convinced the team to replace with Simple Injector :) Commented Jan 24, 2019 at 14:13

1 Answer 1

1

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; }); }); 
Sign up to request clarification or add additional context in comments.

2 Comments

Ill give that a go
You are going to run into problems by getting the service from the service provider within the factory delegate in this case as it my be circular. The general idea of using the factory delegate is correct. You just need to clarify the initialization of the target class.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.