【发布时间】:2014-07-09 22:50:57
【问题描述】:
我目前正在开发一个 .NET MVC 5 网站,我有一个关于提高质量的问题。我从另一个开发人员那里拿到了这个项目,整个项目都有相当多的代码味道,所以我正在尝试清理这个项目。我遇到的问题是大量的类耦合,因此内聚力低。 (为开发者辩护,他的前端 JS 代码非常棒,并且从静态分析工具中获得了非常可靠的分数)。我当前遇到的问题与项目中助手的类耦合有关。这是当前的实现:
...
Type iaccounthelpertype = typeof(IAccountsHelper), igettabletype = typeof(IGettable);
List<Tuple<IAccountsHelper, IGettable>> valid = new List<Tuple<IAccountsHelper, IGettable>>();
// Get all the types that implement IAccountsHelper and IGettable
IEnumerable<Type> types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => iaccounthelpertype.IsAssignableFrom(p) && igettabletype.IsAssignableFrom(p))
.Select(x => x);
foreach (Type type in types)
{
MethodInfo methodInfo = type.GetMethod("Get");
try
{
methodInfo = methodInfo.MakeGenericMethod(typeof(T));
IAccountsHelper helper = methodInfo.Invoke(null, null) as IAccountsHelper;
valid.Add(Tuple.Create<IAccountsHelper, IGettable>(helper, helper as IGettable));
}
catch (NullReferenceException nullref)
{
// this is bad. The new object does not implement the proper static method. So we will carry this exception through.
throw new Exception(type.Name + " does not implement the static generic method Get");
}
catch (ArgumentException e)
{
continue;
}
}
...
此代码允许以下实现(上面的函数名称称为 Get)
IAccountsHelper helper = TheParentClass<UserPrincipal>.Get();
因此,现在任何使用“helper”对象的代码都可以预期该类执行的任何操作都是 UserPrincipal 类型(就像创建用户的 ActiveDirectory 助手一样)。到目前为止,这对于任何需要帮助器的代码单元都有一个更好的实现,而没有更高的耦合率,增加了内聚性。它只是调用这个类,告诉它应该使用什么类型的对象,这个函数会将它映射到适当的类。我做这一切是因为我想不出一种方法来处理 MVC / web api 项目中的依赖注入。但我觉得这段代码很脏,我认为它们可能是实现我正在做的事情的更好方法。有没有人对我能做什么有什么建议,或者这段代码是否不脏等等?
作为说明,我使用 Visual Studio 代码度量窗口来获取项目的类耦合,它从 436 减少到 401,代码行数为 5,909。 (我发现你需要这两者才能很好地估计凝聚力)。
【问题讨论】:
-
为什么你找不到处理依赖注入的方法?你试过用 Nuget 来抓取 Ninject MVC 吗?
-
嗯,这是我试图处理它的一种尝试。不,我还没听说过,我去看看!
标签: c# .net asp.net-mvc architecture