Creating a generic Save () method for models

I have a fairly simple system, and for the purposes of this question there are essentially three parts: models, repositories, application code.

It is based on models. Let me use a simple far-fetched example:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

The same project uses the common repository interface. In the simplest case:

public interface IRepository<T>
{
    T Save(T model);
}

Implementations of this interface are in a separate project and are introduced using StructureMap. For simplicity:

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.
    }
}

So, in the application code, if I wanted to save the model, I would do the following:

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);
    }
}

. , ? , , - , .

+3
2

?

public static T Save<T>(this T current)
{
    var rep = IoCFactory.Current.Container.GetInstance<IRepository<T>>();
    rep.Save(current);
}

ISaveableModel<T>. , , , .

+3

Save() T. ISaveableModel<T>, - BaseModel<T>. T, Save T. T, Save, .

, IRepostory<T>

public interface IRepository<T>
{
    T Save(ISaveableModel<T> model);
}

.

+1

All Articles