我使用https://bitbucket.org/dadhi/dryioc/src/589e7c0b356a/NetCore/src/DryIoc.AspNetCore.Sample作为基线。试图使用以下内容实现基于属性的属性注入选择器:
private static PropertyOrFieldServiceInfo GetImportedPropertiesAndFields(MemberInfo m, Request req)
{
var import = (DependencyAttribute)m.GetAttributes(typeof(DependencyAttribute)).FirstOrDefault();
return import == null ? null : PropertyOrFieldServiceInfo.Of(m)
.WithDetails(ServiceDetails.Of(import.ContractType, import.ContractName), req);
}
其中DependencyAttribute
标记要注入的属性。 没有将此解决方案嵌入到ASP.NET MVC Core应用程序中,它可以正常工作。当我尝试使用{在ASP.NET核心应用程序中使用[Dependency]
属性注入属性时使用{ {1}},它不会工作,只会注入(和拦截)那些类,之后注册的 接管.WithDependencyInjectionAdapter(...)
中的服务(以及{{1}之后)。
我使用的代码部分:
ConfigureServices
DI课程:
.AddDryIoc<TCompositionRoot>
其他信息:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
return services.AddDryIoc<CompositionRoot>();
}
和public static class DI
{
public static readonly PropertiesAndFieldsSelector SelectPropertiesAndFieldsWithDependencyAttribute = PropertiesAndFields.All(withInfo: GetImportedPropertiesAndFields);
public static IServiceProvider AddDryIoc<TCompositionRoot>(this IServiceCollection services)
{
var logger = InfrastructureFactory.CreateDefaultNLogger().CreateLogger<Startup>();
var container = new Container()
.WithDependencyInjectionAdapter(services, throwIfUnresolved: type => type.Name.EndsWith("Controller"))
.With(rules => rules.With(SelectPropertiesAndFieldsWithDependencyAttribute).WithoutThrowOnRegisteringDisposableTransient());
container.RegisterMany<TCompositionRoot>();
container.Resolve<TCompositionRoot>();
logger.LogInformation("Verifying DryIoC resolutions...");
var resolutionErrors = container.VerifyResolutions();
if (resolutionErrors != null && resolutionErrors.Any())
{
foreach (var errors in container.VerifyResolutions())
{
logger.LogError($"DryIoC resolution error for type {errors.Key.ServiceType} : {errors.Value.Message} ({errors.Value.StackTrace})");
}
logger.LogWarning("DryIoC resolutions are WRONG.");
}
else
{
logger.LogInformation("DryIoC resolutions are OK.");
}
return container.Resolve<IServiceProvider>();
}
#region DryIoc Property Dependency Resolver helper
private static PropertyOrFieldServiceInfo GetImportedPropertiesAndFields(MemberInfo m, Request req)
{
var import = (DependencyAttribute)m.GetAttributes(typeof(DependencyAttribute)).FirstOrDefault();
return import == null ? null : PropertyOrFieldServiceInfo.Of(m)
.WithDetails(ServiceDetails.Of(import.ContractType, import.ContractName), req);
}
#endregion
}
的顺序而没有运气。.WithDependencyInjectionAdapter(...)
课程;它很无聊,很长,而且不相关。获取控制器属性注入和控制器方法拦截的任何想法都有效吗?