gpt4 book ai didi

c# - 如何使用 StructureMap 扫描和注册具有属性的类?

转载 作者:行者123 更新时间:2023-11-30 15:07:38 24 4
gpt4 key购买 nike

例如,我想使用 StructureMap 注册所有具有 Service 属性的类

[Service]
public class A {}

最佳答案

据我所知,您需要创建在 StructureMap.Graph 命名空间中找到的自定义 IRegistrationConvention

执行约定

public class ServiceDiscoveryConvention
: StructureMap.Graph.IRegistrationConvention
{
public void Process(Type type, Registry registry)
{
// check if type has attribute
// add to registry using the registry variable
}
}

将约定添加到扫描仪

Scan(cfg =>
{
cfg.TheCallingAssembly(); // or whatever assemblies you are scanning
cfg.Convention<ServiceAttributeConvention>();
});

备注

如果您可以自由决定,您可能希望使用接口(interface)而不是属性。使用接口(interface),您可以为所有类提供通用契约,并且随着项目的增长,它们更容易使用。

属性往往会遍布您的代码,重构它们可能会非常痛苦。在重构方面,接口(interface)具有更好的工具支持。

我正在为类似的任务(插件系统)使用接口(interface),比如

public class TypeScanner<T> : IRegistrationConvention
{
private static readonly Type PluginInterface = typeof(T);

public void Process(Type type, Registry registry)
{
if (type.IsAbstract || type.BaseType == null) return;
if (PluginInterface.IsAssignableFrom(type) == false) return;

registry.For(PluginInterface).Singleton().Add(instance);
}
}

用法类似:

Scan(cfg =>
{
cfg.TheCallingAssembly(); // or whatever assemblies you are scanning
cfg.Convention<TypeScanner<IYourService>>();
});

如果您的约定采用构造函数参数,您可以使用 With:

Scan(cfg =>
{
cfg.TheCallingAssembly(); // or whatever assemblies you are scanning
var convention = new SomeConvention(x,y,z);
cfg.With(convention);
});

关于c# - 如何使用 StructureMap 扫描和注册具有属性的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6406993/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com