# Duplicating .NET Core DI

NOTE: If you are looking for how to access DI services, see this: <span data-annotation-inline-node="true" data-annotation-mark="true" data-card-url="https://oga.atlassian.net/wiki/spaces/~311198967/pages/38305826" data-inline-card="true" data-renderer-start-pos="67"><span class="loader-wrapper"><span data-testid="hover-card-trigger-wrapper" role="button">[<span class="_19itglyw _vchhusvi _r06hglyw _o5721jtm _1nmz9jpi _16d9qvcn _ca0qv77o _u5f31b66 _n3tdv77o _19bv1b66" data-testid="inline-card-icon-and-title"><span class="_19itglyw _vchhusvi _r06hglyw">HowTo Access DI Services</span></span>](https://oga.atlassian.net/wiki/spaces/~311198967/pages/38305826)</span></span></span>

Here are the steps to duplicating the .NET Dependency Injection process, to create a ServiceProvider instance. This is especially useful in unit testing, for classes and services that need the IServiceProvider.

Creating a ServiceProvider takes three steps:

- Initiate the Service Collection
- Register services
- Build the Provider

Below is a method call that does the needed steps, and returns a IServiceProvider.  
It provides a callback

```c#
private IServiceProvider Setup_DI()
{
    // Need a usable reference to the service provider...
    ServiceProvider? _serviceProvider = null;

    // Initiate the service collection...
    IServiceCollection services = new ServiceCollection();


    // Register any services and config to be available via DI...

    //services.Add(new ServiceDescriptor(typeof(InterfaceA), typeof(ClassA), ServiceLifetime.Singleton));
    //services.AddSingleton<InterfaceB, ClassB>();

    // Add a FAKE Object Security Service....
    services.AddScoped<OGA.Auth.OSS.IObjectSecurityService, ObjectSecurityService_Fake>();

    // Declare the remapping class that allows the user management service to look like a directory service, to the User Security Cache...
    // This service is consumed by the constructor of th User Context Caching service.
    services.AddSingleton<OGA.Auth.UserSecContext.IDirectoryService_for_UserSecurityCache_v2, DirectoryService_Adapter_for_USC_v2>();
    // And as well, register the directory service adapter, directly, as we require other methods of it, that are not in the interface...
    services.AddSingleton<DirectoryService_Adapter_for_USC_v2, DirectoryService_Adapter_for_USC_v2>();

    // Declare the User Security Context Caching service...
    // This service provides group membership and account status for the JWT middleware and Object Security Service.
    services.AddScoped<OGA.Auth.UserSecContext.USecContext_CachingAgent_v2>();


    // Create the ServiceProvider, so it can be used...
    _serviceProvider = services.BuildServiceProvider();


    // Return the provider...
    return _serviceProvider;
}
```