Bronzato
Bronzato

Reputation: 9332

Having the repository directly instantiated in the view model

Last week, I downloaded source code of a blog engine developped in ASP.NET MVC3. When analyzing the code, I noticed they used a different way for retrieving data for filling the view model.

Here is an example for the 'post' view model:

The controller:

public ActionResult Details(string slug)
{
    var model = new PostDetailsViewModel(UnitOfWork, slug);         
    return View(model);
}

The view model:

public PostDetailsViewModel(IUnitOfWork unitOfWork, string slug)
    {
        _repository = new PostRepository(unitOfWork);
        Post = _repository.FindBySlug(slug);
    }

The repository:

    public Post FindBySlug(string slug)
    {
        return FindAll().SingleOrDefault(x => x.Slug == slug);
    }

As you can see, the repository is instantiated directly in the view model (in the constructor). Is it a right way?

Usually, I used a business layer and eventually a service layer like this: Controller >> Business >> Repository

Thanks for your advice.

Upvotes: 1

Views: 178

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

Is it a right way?

Doesn't seem to me like a right way. Normally you could do this repository access in the model, not in the view model. Also they seem to have a property called Post in the view model. So they are referencing the domain model in the view model which I wouldn't do.

As far as hardcoding a specific implementation of a repository in the constructor is concerned, well, if you don't care about things like weak coupling between the layers, reusability, maintenance, unit testing, ... you could do it. Nobody can convince us that IoC should always be done. It has its pros and cons.

Upvotes: 2

Related Questions