我有一个相当简单的系统,出于这个问题的目的,基本上由三个部分组成:模型、存储库、应用程序代码。
核心是模型。让我们使用一个简单的例子:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
在同一个项目中有一个通用存储库接口。最简单的说:
public interface IRepository<T>
{
T Save(T model);
}
该接口的实现位于一个单独的项目中,并使用 StructureMap 注入。为了简单起见:
public class PersonRepository : IRepository<Person>
{
public Person Save(Person model)
{
throw new NotImplementedException("I got to the save method!");
// In the repository methods I would interact with the database, or
// potentially with some other service for data persistence. For
// now I'm just using LINQ to SQL to a single database, but in the
// future there will be more databases, external services, etc. all
// abstracted behind here.
}
}
因此,在应用程序代码中,如果我想保存模型,我会这样做:
var rep = IoCFactory.Current.Container.GetInstance<IRepository<Person>>();
myPerson = rep.Save(myPerson);
很简单,但感觉它可以自动化很多。该模式在整个应用程序代码中都适用,因此我想要做的是创建一个通用的Save()
在所有模型上,这只是对上述应用程序代码的简写调用。这样人们只需要调用:
myPerson.Save();
但我似乎无法找到一种方法来做到这一点。也许这很简单,只是我没有从正确的角度看待它。起初我尝试创建一个空的ISaveableModel<T>
接口并打算让每个“可保存”模型实现它,然后对于单个通用Save()
方法我会在界面上进行扩展:
public static void Save<T>(this ISaveableModel<T> model)
{
var rep = IoCFactory.Current.Container.GetInstance<IRepository<T>>();
model = rep.Save(model);
}
但它告诉我rep.Save(model)
有无效参数。看起来它并没有像我希望的那样连接类型推断。我尝试了类似的方法BaseModel<T>
模型将从中继承的类:
public class BaseModel<T>
{
public void Save()
{
this = IoCFactory.Current.Container.GetInstance<IRepository<T>>().Save(this);
}
}
但编译器错误是一样的。有没有办法实现我想要实现的目标?我对设计非常灵活,所以如果我在架构层面上遇到了一些错误,那么我有空间退后一步并改变大局。