DI dependency injection of unity (mvc)
A .nuget download and install:
Use Nuget installation Unity.MVC
And automatically generates UnityMvcActivator.cs UnityConfig.cs file at ~ / App_Start / directory after installation
Second configuration:
UnityConfig code opens the file, modifying registerTypes () method
public static void RegisterTypes(IUnityContainer container) { // NOTE: To load from web.config uncomment the line below. // Make sure to add a Unity.Configuration to the using statements. // container.LoadConfiguration(); // TODO: Register your type's mappings here. // container.RegisterType<IProductRepository, ProductRepository>(); // increase the interface and its implementation class they need injected container.RegisterType <IUserDAL, UserDAL> (); container.RegisterType<IUserBLL, UserBLL>(); }
Second, use: [Note the difference between implementation and contrast, will be easier to learn]
1. Code injection mode
(1) constructor injection (recommended):
public class UserController : Controller { public UserController(IUserBLL userBLL) { this.userBLL = userBLL; } IUserBLL userBLL; // GET: User public ActionResult Index() { var list = userBLL.GetUserModels(); return View(list); } }
(2) injection properties:
namespace ZLP.Web.Controllers { public class UserController : Controller { [Dependency] public IUserBLL userBLL { get; set; } // GET: User public ActionResult Index() { var list = userBLL.GetUserModels(); return View(list); } } }
Error: System.NullReferenceException: "Object reference not set to an instance of an object."
Solution:
1. To give increased Dependency injection characteristic property, remember
2. whether the reference is using Unity namespace, do wrong (using System.Runtime.CompilerServices;)
3. Properties of whether to use public access modifier
(3) Method injection:
2. Profiles injection (recommended)
Three common problems: