You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
3.1 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using DS.Module.Core.Attributes;
using DS.Module.Core.Extensions;
using DS.Module.Core.Reflection;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
namespace DS.Module.Core.Modules;
/// <summary>
/// 自动注入模块继承与SuktAppModuleBase类进行实现
/// </summary>
public class DependencyAppModule : DSAppModule
{
public override void ConfigureServices(ConfigureServicesContext context)
{
var services = context.Services;
AddAutoInjection(services);
}
private void AddAutoInjection(IServiceCollection services)
{
var typeFinder = services.GetOrAddSingletonService<ITypeFinder, TypeFinder>();
var baseTypes = new Type[]
{ typeof(IScopedDependency), typeof(ITransientDependency), typeof(ISingletonDependency) };
var types = typeFinder.FindAll().Distinct();
types = types.Where(type =>
type.IsClass && !type.IsAbstract && (baseTypes.Any(b => b.IsAssignableFrom(type))) ||
type.GetCustomAttribute<DependencyAttribute>() != null);
foreach (var implementedInterType in types)
{
var attr = implementedInterType.GetCustomAttribute<DependencyAttribute>();
var typeInfo = implementedInterType.GetTypeInfo();
var serviceTypes = typeInfo.ImplementedInterfaces
.Where(x => x.HasMatchingGenericArity(typeInfo) && !x.HasAttribute<IgnoreDependencyAttribute>() &&
x != typeof(IDisposable)).Select(t => t.GetRegistrationType(typeInfo));
var lifetime = GetServiceLifetime(implementedInterType);
if (lifetime == null)
{
break;
}
if (serviceTypes.Count() == 0)
{
services.Add(new ServiceDescriptor(implementedInterType, implementedInterType, lifetime.Value));
continue;
}
if (attr?.AddSelf == true)
{
services.Add(new ServiceDescriptor(implementedInterType, implementedInterType, lifetime.Value));
}
foreach (var serviceType in serviceTypes.Where(o => !o.HasAttribute<IgnoreDependencyAttribute>()))
{
Console.WriteLine(serviceType);
services.Add(new ServiceDescriptor(serviceType, implementedInterType, lifetime.Value));
}
}
}
private ServiceLifetime? GetServiceLifetime(Type type)
{
var attr = type.GetCustomAttribute<DependencyAttribute>();
if (attr != null)
{
return attr.Lifetime;
}
if (typeof(IScopedDependency).IsAssignableFrom(type))
{
return ServiceLifetime.Scoped;
}
if (typeof(ITransientDependency).IsAssignableFrom(type))
{
return ServiceLifetime.Transient;
}
if (typeof(ISingletonDependency).IsAssignableFrom(type))
{
return ServiceLifetime.Singleton;
}
return null;
}
public override void ApplicationInitialization(ApplicationContext context)
{
var app = context.GetApplicationBuilder();
}
}