Lasse Edsvik
Lasse Edsvik

Reputation: 9298

Use repository in referenced dll using entity framework

I have created a DLL that contains lots of authentication and user management that I'm trying to use in a separate project (MVC 3 Website).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestProj.Authentication;

namespace TestSite.MVC.Areas.Admin.Controllers
{
    public class TestController : Controller
    {     
        AuthenticationRepository authrep = new AuthenticationRepository();

        public ActionResult Index()
        {
            authrep.DeleteUser(1);
            return View();
        }
    }
}

Now this obviously does'nt work, which is understandable.

Is it dependency injection I need here?
And in that case, how would the basic code look for that?
Do I need to add something in the constructor for the referenced DLL?

Upvotes: 0

Views: 329

Answers (1)

Jason Evans
Jason Evans

Reputation: 29186

Try structuring your controller like this:

public class TestController : Controller
    {     
        IAuthenticationRepository AuthenticationRepository { get;set; }

        public void TestController (IuthenticationRepository authenticationRepository)  
        {
          this.AuthenticationRepository = authenticationRepository;
        }

        public ActionResult Index()
        {
            this.AuthenticationRepository.DeleteUser(1);

            return View();
        }
    }

Create an interface for your repository. You could then use a DI framework (like Ninject for MVC 3) to inject instances of AuthenticationRepository into usages of IAuthenticationRepository.

https://github.com/ninject/ninject/wiki

Upvotes: 2

Related Questions