C# Unity IOC-如何基于自定义属性注册类型?

C# Unity IOC-如何基于自定义属性注册类型?,c#,asp.net,inversion-of-control,unity-container,ioc-container,C#,Asp.net,Inversion Of Control,Unity Container,Ioc Container,我有一个大型ASP.Net web应用程序,它使用Unity IOC。有许多类需要创建为单例 这是启动项目中UnityConfig.cs中代码的第一部分: // Create new Unity Container var container = new UnityContainer(); // Register All Types by Convention by default container.RegisterTypes( AllClasses.FromLoadedAssemb

我有一个大型ASP.Net web应用程序,它使用Unity IOC。有许多类需要创建为单例

这是启动项目中UnityConfig.cs中代码的第一部分:

// Create new Unity Container
var container = new UnityContainer();

// Register All Types by Convention by default
container.RegisterTypes(
    AllClasses.FromLoadedAssemblies(),
    WithMappings.FromMatchingInterface,
    WithName.Default,
    WithLifetime.Transient);
到目前为止,我已经在Unity IOC容器中向lifetime manager专门注册了每个单例类型,如下所示:

container.RegisterType<IMySingleton1, MySingleton1>(new ContainerControlledLifetimeManager());
container.RegisterType<IMySingleton2, MySingleton2>(new ContainerControlledLifetimeManager());
并相应地标记了类定义:

[Singleton]
public class MySingleton : IMySingleton
{
 ...
}
我已成功选择具有此自定义属性的所有类型:

static IEnumerable<Type> GetTypesWithSingletonAttribute(Assembly assembly)
{
    foreach (Type type in assembly.GetTypes())
    {
        if (type.GetCustomAttributes(typeof(SingletonAttribute), true).Length > 0)
        {
            yield return type;
        }
    }
}
container.RegisterTypes(
    AllClasses.FromLoadedAssemblies()
        .Where(t => t.GetCustomAttributes<SingletonAttribute>(true).Any()),
    WithMappings.FromMatchingInterface,
    WithName.Default,
    WithLifetime.ContainerControlled);
静态IEnumerable GetTypeSwithSingleton属性(程序集)
{
foreach(在assembly.GetTypes()中键入Type)
{
if(type.GetCustomAttributes(typeof(SingletonAttribute),true).Length>0)
{
收益型;
}
}
}
我在UnityConfig.cs中有以下代码:

// Identify Singleton Types
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

List<Type> singletonTypes = new List<Type>();
foreach (var assembly in assemblies)
{
    singletonTypes.AddRange(GetTypesWithSingletonAttribute(assembly));
}
//识别单例类型
Assembly[]assemblies=AppDomain.CurrentDomain.GetAssemblies();
List singletonTypes=新列表();
foreach(程序集中的变量程序集)
{
AddRange(GetTypesWithSingletonAttribute(assembly));
}
因此,我现在有了一个包含所有必需类型的枚举,但我看不出如何按类型将它们注册为Singleton,同时仍然能够通过约定解析它们(即,Unity知道IMySingleton应该解析为MySingleton的一个实例)


有人能解释一下吗?

您只需要将返回的类型约束为使用
Singleton
属性注释的类型:

static IEnumerable<Type> GetTypesWithSingletonAttribute(Assembly assembly)
{
    foreach (Type type in assembly.GetTypes())
    {
        if (type.GetCustomAttributes(typeof(SingletonAttribute), true).Length > 0)
        {
            yield return type;
        }
    }
}
container.RegisterTypes(
    AllClasses.FromLoadedAssemblies()
        .Where(t => t.GetCustomAttributes<SingletonAttribute>(true).Any()),
    WithMappings.FromMatchingInterface,
    WithName.Default,
    WithLifetime.ContainerControlled);

天才!这正是我想要的。非常感谢。:)