Skip to content
This repository has been archived by the owner on May 30, 2024. It is now read-only.

Class library meant to ease configuration and registration of services, database contexts and option files in .NET 5.0 web app projects.

Notifications You must be signed in to change notification settings

tommasodotNET/web-app-service-library

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

82 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

WebAppServiceLibrary

Publish Packages package

This class library is meant to ease configuration and registration of services, database contexts and option files in .NET 5.0 web app projects.

Installation and configuration

Install package from nuget gallery using either dotnet CLI

dotnet add package ServiceLibrary.WebApp

or the package manager

Install-Package ServiceLibrary.WebApp

Register all the configured services adding this line in the startup:

services.ConfigureService(Configuration);

Configuring services

Services registered with DI are usually interface's implementations. Starting froma a generic interface IService, the implementation would be

public interface Service : IService

To have this automatic registered by this class library, we just add one attribute

[Service(typeof(IService), ServiceLifetime.Scoped)]
public interface Service : IService

This is the equivalent of adding

services.AddScoped<IService, Service>();

in the startup.cs. By changing the values of the second parameter we can select the lifetime of the service (scoped, singleton, ...). If the Service does not implement any interface, we can simply leave first attribute null.

Configuring databases

Databases can be easily configured adding the attribute

[Database("ConnectionString")]
public class MyDbContext : DbContext

This is the equivalent of adding

services.AddDbContext<MyDbContext>(options => options.UseSqlite("Data Source=<connection_string>"));

in the startup.cs.

The string parameter is the name of the json attribute in the appsettings.json file which holds the value for the connection string.

Configuring options

Options can be easily configured adding the attribute

[Option("JsonSections")]
public class MySettings

This is the equivalent of adding

// Add functionality to inject IOptions<T>
services.AddOptions();

// Add our Config object so it can be injected
services.Configure<MySettings>(Configuration.GetSection("JsonSections"));

in the startup.cs.

The string parameter is the name of the json section in the appsettings.json file which we want to map to our model. Every attribute in the json object needs to have a correspondent property in the model.

About

Class library meant to ease configuration and registration of services, database contexts and option files in .NET 5.0 web app projects.

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages