Skip to content

Latest commit

 

History

History
91 lines (59 loc) · 2.44 KB

File metadata and controls

91 lines (59 loc) · 2.44 KB

StowayNet.Extensions.DependencyInjection            中文

StowayNet.Extensions.DependencyInjection is Dependency Injection extension methods for .net 5, it can easily implement dependency injection.

Get Started

NuGet

You can run the following command to install the StowayNet.Extensions.DependencyInjection in your project.

PM> Install-Package StowayNet.Extensions.DependencyInjection

Configuration

First,You need to config StowayNet.Extensions.DependencyInjection in your Startup.cs:

......
using StowayNet;
......

public void ConfigureServices(IServiceCollection services)
{
    ......

    services.AddStowayNet();

    ......
}

Sample

Sample 1:implement IStowayDependency empty interface

IStowayDependency is an empty interface, all class and its subclasses that implement IStowayDependency interface will injected into Transient lifecyle。

public class BookService : IStowayDependency
{
    ......
}

If you want to inject Scoped and Singleton lifecycle, you need to add the attribute StowayDependencyAttribute to class.

Sample 2:StowayDependencyAttribute

Adding the attribute StowayDependencyAttribute to class, specifying the StowayDependencyType parameter, the lifecycles of TransientScopedSingleton can be injected, the attribute can be inherited by derived classes.

[StowayDependency(StowayDependencyType.Scoped)]
public class BookService {

}

......

[StowayDependency(StowayDependencyType.Singleton)]
public class AuthorService {

}

Sample 3:implement Register method of IStowayServiceRegister interface.

By implementing Register method of IStowayServiceRegister interface, you can implement a custom injection service.

internal class PressServiceRegister : IStowayServiceRegister
{
  public void Register(IServiceCollection services, List<Type> types, IConfiguration configuration)
  {
      var serviceType = typeof(IBookService);
      var stTypes = types.Where(t => !t.IsAbstract && !t.IsInterface).ToList();

      services.RegisterTypes(stTypes, ServiceLifetime.Scoped, true, true);
  }
}

At the same time, the configuration of other third-party frameworks can also be managed in this way.