Skip to content

Using the package

Joshua Hegedus edited this page Nov 5, 2023 · 8 revisions

There are two main ways to use the package.

  • Registering your classes in the same collection that you need for registering this module. (Recommended)
  • Passing the IServiceProvider through the constructor.

Registering your own classes

Registering in a separate class

You can create a "Module" for your project by creating a new class and implementing the IModule from the joshika39.Core.

Let's say you have a PdfService and a MyLogger class that you want to register. First you need to create a module class:

internal class MyModule : IModule 
{
    public void LoadModules(IServiceCollection collection)
    {
        // Do your class registrations
	
        // Read about lifecycles here: https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection-guidelines
        collection.AddSingleton<PdfService>();
        collection.AddScoped<MyLogger>();		
    }
}

Then you just have to call your module's LoadModules function:

var collection = new ServiceCollection();  
new CoreModule().LoadModules(collection, "reader-tests"); 
new MyModule().LoadModules(collection);
var provider = collection.BuildServiceProvider();

Registering directly in the composition root

This is a the same if you take out the core of your LoadModules function from to previous example

var collection = new ServiceCollection();  
new CoreModule().LoadModules(collection, "reader-tests"); 

// Do your class registrations	
// Read about lifecycles here: https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection-guidelines
collection.AddSingleton<PdfService>();
collection.AddScoped<MyLogger>();	

var provider = collection.BuildServiceProvider();

References

Clone this wiki locally