Skip to content

Instantly share code, notes, and snippets.

@dls314
Last active August 14, 2017 12:52
Show Gist options
  • Save dls314/29b3dab74a00e9de403994d8e71e5887 to your computer and use it in GitHub Desktop.
Save dls314/29b3dab74a00e9de403994d8e71e5887 to your computer and use it in GitHub Desktop.
ASP.NET Core 2 Dependency Injection Shared Singleton Service Collection Example
using System;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
namespace ServiceCollectionExample
{
public class Foo { }
[Route("api/[controller]")]
public class FooController : Controller
{
private readonly Foo _foo;
public FooController(Foo foo) => _foo = foo;
[HttpGet]
public string Get() => $"foo.GetHashCode() is {_foo.GetHashCode()}";
}
public class Startup
{
public void ConfigureServices(IServiceCollection services) => services.AddMvc();
public void Configure(IApplicationBuilder app, IHostingEnvironment env) => app.UseMvc();
}
public class Program
{
public static void Main(string[] args)
{
var services = new ServiceCollection().AddSingleton<Foo>();
var provider = services.BuildServiceProvider();
var webHost = WebHost.CreateDefaultBuilder(args)
.ConfigureServices(services2 =>
{
foreach (var service in services)
{
if (service.Lifetime == ServiceLifetime.Singleton)
services2.AddSingleton(service.ServiceType, provider.GetService(service.ServiceType));
}
})
.UseStartup<Startup>()
.Build();
Console.WriteLine($"provider.GetService<Foo>().GetHashCode() is {provider.GetService<Foo>().GetHashCode()}");
webHost.Run();
}
}
}
@odannyboy000
Copy link

services2.AddSingleton(service.ServiceType, provider.GetService(service.ServiceType));

Doesn't provider.GetService cause the instance to be created?

Also, I read that GetHashCode isn't guaranteed to be unique. Perhaps a debug statement or guid generator in the ctor would prove these are the same instances.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment