. net core service injection without interface

Three life cycles of dependency injection in. net core ...

Three life cycles of dependency injection in. net core

To implement dependency injection without interface, first of all, we must understand what dependency injection is. There are still a lot of online materials. I won't write them in detail here. I don't write the interface specifically, but I want to realize dependency injection. How to implement it concretely.

The first thing to know is that. net core provides three lifecycles, most of which are basically the second by default.

public enum ScopeEnum { // Only 1 instance in the entire application lifecycle Singleton, //Initializing only one instance in the same scope can be understood as only one instance in the same scope Scope, // Each time you create an object, it's different Transient }

Step 2 find out the service

Use the method of the feature to find the method that needs to implement the interface for the class

var serviceTypes = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(s => s.DefinedTypes.Where(t => t.GetCustomAttribute<ServiceAttribute>(false) != null)) .ToArray();

The third step is to loop the feature and inject the acquired set with dependency

Find out whether the interface still exists and the type of life cycle through the attribute

Underline_ It is a 7.0 feature, which means it is discarded and no longer used

foreach(var type in serviceTypes) { var serviceAttribute = type.GetCustomAttribute<ServiceAttribute>(); var scopeType = serviceAttribute?.ScopeType ?? ScopeEnum.Scope; var interfaceType = serviceAttribute?.InterfaceType ?? type.GetInterface($"I"); var _ = interfaceType == null ? AddInstance(scopeType, service, type) : AddByInterface(scopeType, service, interfaceType, type); } return service;

Feature setting is very simple, that is, creating a new class and implementing parameter setting in the constructor

public class ServiceAttribute : Attribute { public ScopeEnum ScopeType { get; set; } public Type InterfaceType { get; set; } public ServiceAttribute(Type interfaceType=null,ScopeEnum scope = ScopeEnum.Scope) { InterfaceType= interfaceType; ScopeType = scope; } }

Then add it to ConfigureServices (used to configure dependency injection to create objects based on dependency at runtime) services.AddIocServiceScanner();

Add properties to corresponding classes

It can realize the use of dependency injection without interface.

4 June 2020, 15:20 | Views: 5486

Add new comment

For adding a comment, please log in
or create account

0 comments