ASP.NET Core 자동 종속 주입 구현
그래서 자주 반복적인 동작을 합니다. 인터페이스 정의->쓰기 실현 클래스->주입
때때로 Add를 쓰는 것을 잊어버리고 화면에 잘못 보고된 것을 보고 멍한 표정을 지으며 순간적으로 반응하여 주입을 잊어버리는 경우도 있다.빨리 서비스 컬렉션을 보충하세요.AddXX
많은 개원 프레임워크가 이미 유사한 작업을 실현했다고 말하지만, 예를 들어 AutoFac, Unity 등은 주입 프레임워크에 의존한다.그러나 이 창고들은 모두 너무 방대하기 때문에 나는 개인적으로 경량급의 실현을 좋아한다.
매거 정의
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class AutoInjectAttribute : Attribute
{
public AutoInjectAttribute(Type interfaceType, InjectType injectType)
{
Type = interfaceType;
InjectType = injectType;
}
public Type Type { get; set; }
/// <summary>
///
/// </summary>
public InjectType InjectType { get; set; }
}
세 가지 주입 유형 정의
/// <summary>
///
/// </summary>
public enum InjectType
{
Scope,
Single,
Transient
}
실행 디렉터리에 있는 모든 dll을 스캔하여 자동 주입합니다
/// <summary>
///
/// </summary>
public static class AutoInject
{
/// <summary>
/// InjectAttribute
/// </summary>
/// <param name="serviceCollection"></param>
/// <returns></returns>
public static IServiceCollection AddAutoDi(this IServiceCollection serviceCollection)
{
var path = AppDomain.CurrentDomain.BaseDirectory;
var assemblies = Directory.GetFiles(path, "*.dll").Select(Assembly.LoadFrom).ToList();
foreach (var assembly in assemblies)
{
var types = assembly.GetTypes().Where(a => a.GetCustomAttribute<AutoInjectAttribute>() != null)
.ToList();
if (types.Count <= 0) continue;
foreach (var type in types)
{
var attr = type.GetCustomAttribute<AutoInjectAttribute>();
if (attr?.Type == null) continue;
switch (attr.InjectType)
{
case InjectType.Scope:
serviceCollection.AddScoped(attr.Type, type);
break;
case InjectType.Single:
serviceCollection.AddSingleton(attr.Type, type);
break;
case InjectType.Transient:
serviceCollection.AddTransient(attr.Type, type);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
return serviceCollection;
}
}
자동 의존 주입 기능 사용
public void ConfigureServices(IServiceCollection services)
{
services.AddAutoDi();
}
public interface ITest
{
string Say();
}
[AutoInject(typeof(ITest),InjectType.Scope)]
public class Test : ITest
{
public String Say()
{
return "test:"+DateTime.Now.ToString();
}
}
다시 프로그램을 실행하면 모든 부착AutoInject
의 모든 실현 클래스가 asp에 주입됩니다.net 코어의 의존은 용기에 주입됩니다.지금까지 ASP였습니다.NET Core 구현 자동 종속 주입의 상세한 내용, ASP에 대한 추가 정보.NET Core는 자동으로 주입된 자료에 의존합니다. 저희의 다른 관련 글에 주목하세요!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
부트스트랩 ASP.NET에서 설정하는 법1) _Layout.cshtml 內 link로 bootstrap 참조 2) Nuget 패키지에서 BootStrap 다운로드 3) 하단 부트스트랩 예제 사이트 참고해서 프로젝트 개발 참고 :...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.