using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Manjinba.Communication.Common.Attributes
{
/// <summary>
///
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class IMVersionAttribute : Attribute
{
/// <summary>
///
/// </summary>
public string Name { get; set; }
/// <summary>
///
/// </summary>
/// <param name="name"></param>
public IMVersionAttribute(string name)
{
Name = name;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Manjinba.Communication.Common.Attributes;
namespace Manjinba.Communication.Common.Utils
{
/// <summary>
///
/// </summary>
public class VersionManager
{
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="assembly"></param>
/// <param name="version"></param>
/// <returns></returns>
public static T GetInstance<T>(Assembly assembly, string version) where T : class
{
T result = default(T);
Type type = typeof(T);
var types = assembly.GetTypes().Where(a => type.IsAssignableFrom(a));
List<string> versions = new List<string>();
foreach (var c in types)
{
IMVersionAttribute attr = (IMVersionAttribute)c.GetCustomAttribute(typeof(IMVersionAttribute));
if (attr == null)
{
if (string.IsNullOrEmpty(version))
{
return (Activator.CreateInstance(c) as T);
}
}
else
{
if (version == attr.Name)
{
return (Activator.CreateInstance(c) as T);
}
versions.Add(attr.Name);
}
}
if (versions.Count > 0)
{
versions.Sort();
string maxVersion = versions[versions.Count - 1];
foreach (var c in types)
{
IMVersionAttribute attr = (IMVersionAttribute)c.GetCustomAttribute(typeof(IMVersionAttribute));
if (attr != null && attr.Name == maxVersion)
{
return (Activator.CreateInstance(c) as T);
}
}
}
return result;
}
}
}
调用:
IUserRepository userRepository = VersionManager.GetInstance<IUserRepository>(assembly, request.version);