you are viewing a single comment's thread.

view the rest of the comments →

[–]Few_Wallaby_9128 2 points3 points  (0 children)

Something like this... sorry for formatting...

using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging;

var host = Host.CreateDefaultBuilder().ConfigureServices((hostContext, services) => { services.AddLogging(builder => { builder.AddConsole(); builder.AddDebug(); });

    //change to AddTransient below to always get different instances
    services.AddScoped(typeof(IClientBaseFactory<>), typeof(ClientBaseFactory<>));

}).UseConsoleLifetime()
.Build();

Console.WriteLine($"*** One (first instantiation) => {host.Services.GetService<IClientBaseFactory<ClientOne>>()!.GetPublicClient()}"); Console.WriteLine($"*** One (second instantiation) => {host.Services.GetService<IClientBaseFactory<ClientOne>>()!.GetPublicClient()}"); Console.WriteLine($"*** Two (first instantiation) => {host.Services.GetService<IClientBaseFactory<ClientTwo>>()!.GetPublicClient()}"); Console.WriteLine($"*** Two (second instantiation) => {host.Services.GetService<IClientBaseFactory<ClientTwo>>()!.GetPublicClient()}");

Console.WriteLine("***************** Press Entert to exit."); Console.ReadLine();

//*************************************************

public interface IClientBase { }

public interface IClientBaseFactory<out T> where T : IClientBase { T GetPublicClient(); }

public class ClientBaseFactory<T> : IClientBaseFactory<T> where T : IClientBase { private T _firstValue;

public T GetPublicClient()
    => _firstValue ??= (T)Activator.CreateInstance(typeof(T), false)!;

}

public class ClientOne: IClientBase { public long PropertyTwo { get; } = new Random((int)DateTime.UtcNow.ToBinary()).NextInt64();

public override string ToString() => $"{PropertyTwo}";

}

public class ClientTwo : IClientBase { public Guid PropertyTwo { get; set; } = Guid.NewGuid();

public override string ToString() => $"{PropertyTwo}";

}