Dependency Injection in .NET with examples?

前端 未结 8 1460
别跟我提以往
别跟我提以往 2020-11-27 14:31

Can someone explain dependency injection with a basic .NET example and provide a few links to .NET resources to extend on

相关标签:
8条回答
  • 2020-11-27 15:29

    Create DB layer project(class library) and add below code in it.

    public class UserData : IUserData
    {
        public string getUserDetails()
        {
            return "Asif";
        }
    }
    
    public interface IUserData
    {
        string getUserDetails();
    }
    
    0 讨论(0)
  • 2020-11-27 15:31

    Add bussiness logic project of type class library and add below code in it. public class UserDetailLogic : IUserDetailLogic { private IUserData _userData = null;

        public UserDetailLogic(IUserData userData)
        {
            _userData = userData;
        }
        public string getUserDetails()
        {
            return _userData.getUserDetails();
        }
    }
    
    public interface IUserDetailLogic
    {
        string getUserDetails();
    }
    

    In you main project add below code in home controller.

    public class HomeController : Controller { private readonly IUserDetailLogic _userDetailLogic;

        public HomeController(IUserDetailLogic userDetailLogic)
        {
            _userDetailLogic = userDetailLogic;
        }
    
        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
            string str = _userDetailLogic.getUserDetails();
            return View();
        }
    
        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";
    
            return View();
        }
    
        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";
    
            return View();
        }
    }
    
    0 讨论(0)
提交回复
热议问题