0

AspNetCore Web application has more than 100 services that are available via ServiceProvider and can be view in ServiceCollection list. Example services: IConfigurtion, IConfiguration provider, etc.

How to register all these dependencies for Unit Test project.

I guess, In Web Project these dependencies are register in 'WebHost.CreateDefaultBuilder' method.

public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseKestrel(options => options.AddServerHeader = false)
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();
    } 

In my Unit Test Project. I can register these services one by one, but it is not efficient looking at the so long list of dependencies.

services.AddSingleton<IConfiguration, ConfigurationRoot>();

I might not need them all but it is cumbersome running Unit test project and finding that this initialization failed or that, etc.

Note: Registering DbContext with below syntax is Registering around 12 services.

services.AddDbContext<AppDbContext>(options =>
              options.UseInMemoryDatabase("Db"),
              ServiceLifetime.Scoped
              );

So my question, Is there any method/s that i can call so that Dependencies are resolved correctly for my UnitTest project as they happen with Web Project.

Note: I can handle those services that are registered by me in Web. I am only concerned about those that are registered behind that scene by the Framework.

Any help is appreciated. Thank you!

Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
Irshad Ali
  • 1,153
  • 1
  • 13
  • 39
  • 1
    Did you see this comment ? https://stackoverflow.com/a/46437144/2057653 It helped me while I was working on console app. – ibrahimozgon Mar 08 '19 at 11:42
  • It is a useful link @ibrahimozgon. Thank you. I have resolved the issue of IConfiguration and IConfigurationProvider using ConfigurationBuilder by seeing in AspNetCore project from github. Thanks to OpenSource. There is a method named BuildCommonServices. It was quite useful. Although I am not sure, if some other dependency will become issue going forward. – Irshad Ali Mar 08 '19 at 12:06

0 Answers0