saleh azami
saleh azami

Reputation: 13

how to implement dependency injection in mvc?

I'm trying to implement dependency injection but i know how to implement the interface and repository of classes then i don't know what shall i do. This my sample:

 public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string LastName { get; set; }
}

This is my interface:

public interface IUser
{
   IEnumerable<User> GetUsers();
   void AddUser(User user);
   void EditUser(User user);
   void DeleteUser(int id);
   User UserGetById(int id);
   void Save();
}

This is my repository:

  public class UserRepsitory:IUser
{
    private _Context _context;
    public UserRepsitory(_Context _context)
    {
        this._context = _context;
    }
    public IEnumerable<User> GetUsers()
    {
       return  _context.User.ToList();
    }
    public void AddUser(User user)
    {
        _context.User.Add(user);
    }
    public void EditUser(User user)
    {

        _context.Entry(user).State = System.Data.Entity.EntityState.Modified;
    }
    public User UserGetById(int id)
    {
       return _context.User.Find(id);
    }
    public void Save()
    {
        _context.SaveChanges();
    }
    public void DeleteUser(int id)
    {
        var Search = _context.User.Find(id);
        _context.User.Remove(Search);

    }
}

And one of method in controller:

  private IUser userRepsitory;

    public UsersController()
    {
        this.userRepsitory = new UserRepsitory(new _Context());
    }

    public UsersController(IUser UserRepository)
    {
        this.userRepsitory = UserRepository;
    } 

    public ActionResult Index()
    {
        return View(userRepsitory.GetUsers());
    }

What is the next step?

Upvotes: 1

Views: 352

Answers (2)

Ankit Lalan
Ankit Lalan

Reputation: 1

In order to create and configure your project with Spring DI(Dependency Feature) you must configure beans. Create an xml file (if its not there) and add references to bean

In this xml file, provide references to the classes you want to inject. Example:

<bean id="Name of the JAVA Class" class="the Full path of the JAVA class"/>

And in your class where you are supposed to call the referencing class(above), calling procedure would be like :

@Controller
public class MyController {

private full.path.of.my.class.named.MyJavaClass _class;

@Autowired
private MyController (full.path.of.my.class.MyJavaClass  class)
{
        this._class= class;
}
}

Now say if you a function in MyJavaClass

public int sum(int x, int y){
return x+y;
}

Then without creating object of MyJavaClass you can inject like the following in your controller:

_class.Sum(10,15);

YOU DO NOT CREATE AN INSTANCE OF THIS CLASS.

Upvotes: 0

Shyju
Shyju

Reputation: 218862

The first thing is, get rid of the default constructor where we are hard coding the initialization of UserRepository ! We will do that in the dependency injection way.

public UsersController : Controller
{ 
    private readonly IUser userRepsitory;
    public UsersController(IUser UserRepository)
    {
        this.userRepsitory = UserRepository;
    } 

    public ActionResult Index()
    {
        return View(userRepsitory.GetUsers());
    }
}

Now we need something to tell the MVC framework which version/implementation of IUser should be used when the code runs. you can use any dependency injection frameworks to do that. For example, If you are in MVC 6, you can use the inbuilt dependency injection framework to do that. So go to your Startup class and in your ConfigureServices method, you can map an interface to a concrete implementation.

public class Startup
{
  public void ConfigureServices(IServiceCollection services)
  {
     services.AddTransient<IUser, UserRepository>();
  }
}

If you are in a previous version of MVC, you may consider using any of the dependency injection frameworks available like Unity, Ninject etc.

It is pretty much same, you map an interface to a concrete implementation

Ninject

private static void RegisterServices(IKernel kernel)
{
  kernel.Bind<IUser>().To<UserRepository>();
}

You do not need to put the mapping in a cs file. You can define that in a config file. For example, when you use Unity you can do something like this in your config file (web config or an external config file for unity configuration)

Unity

<alias alias="IUser" type="YourNamespace.IUser, YourAssemblyName" />
<register type="IUser" mapTo="YourNamespace.UseRepository, YourAssemblyName">

Upvotes: 1

Related Questions