C# Ioc ASP.NET MVC Dependency Injection

时间:2023-03-09 00:43:18
C# Ioc ASP.NET MVC Dependency Injection

ASP.NET MVC Dependency Injection

同志们,非常快速的Ioc注册接口和注入Mvc Controller,步骤如下:

安装Unity.Mvc NuGet Package 在你的项目中,打开Package Manager Console进行安装。

C# Ioc ASP.NET MVC Dependency Injection

接下来我们可以看见两个类文件UnityConfig.cs 和 UnityMvcActivator.cs,接口注册需要在UnityConfig.cs里写你的接口实例,UnityMvcActivator.cs 它会帮助你自动resolver,放心吧,这个工具太无脑了,需要做的不多

1.注册接口

 public static class UnityConfig
{
#region Unity Container
private static Lazy<IUnityContainer> container =
new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
}); /// <summary>
/// Configured Unity Container.
/// </summary>
public static IUnityContainer Container => container.Value;
#endregion /// <summary>
/// Registers the type mappings with the Unity container.
/// </summary>
/// <param name="container">The unity container to configure.</param>
/// <remarks>
/// There is no need to register concrete types such as controllers or
/// API controllers (unless you want to change the defaults), as Unity
/// allows resolving a concrete type even if it was not previously
/// registered.
/// </remarks>
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>();
container.RegisterType<IRepository, RepositoryImpl>();
}

  2.注入接口到Controller

 public class HomeController : Controller
{
private IRepository _repository;
public HomeController(IRepository repository)
{
_repository = repository;
} public ActionResult Index()
{
var result = _repository.Test();
return View(result);
}

  3.启动Ioc初始化,代码在Global.asax

 public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
UnityConfig.RegisterTypes(new UnityContainer());
}
}

  少年F5启动你的程序,见证奇迹的时刻,最快速的搭建.net Mvc Ioc 接口实例以及Controller的依赖注入。