码迷,mamicode.com
首页 > Windows程序 > 详细

C# Ioc 接口注册实例以及注入MVC Controller

时间:2018-02-07 14:42:01      阅读:1896      评论:0      收藏:0      [点我收藏+]

标签:void   middle   prot   exe   ret   文件   构造函数   接口   mod   

当弄一个小程序时,就忽略了使用Ioc这种手段,作为一个帅气程序员,代码规范,你懂的~,废话不多说,快速搭建一个Ioc接口实例以及直接注入到 MVC Controller 构造函数中如下:

MVC integration requires the Autofac.Mvc5 NuGet package.

文档:http://docs.autofac.org/en/latest/integration/mvc.html#register-controllers

代码如下:

1.首先我们创建一个WebContainer.cs 类文件,代码如下:

using System.Web;
using System.Web.Mvc;
using Autofac;
using Autofac.Core;
using Autofac.Integration.Mvc;

namespace Dlw.MiddleService.Ioc
{
public class WebContainer
{
internal static IContainer Container { get; set; }
public static void Initialize(IModule webComponentsModule)
{
var builder = new ContainerBuilder();

builder.RegisterModule(webComponentsModule);
builder.RegisterModule<AutofacWebTypesModule>();
Container = builder.Build();
DependencyResolver.SetResolver(new Autofac.Integration.Mvc.AutofacDependencyResolver(Container));

}
public static T Resolve<T>()
{
// In case of a background thread, the DependencyResolver will not be able to find
// the appropriate lifetime, which will result in an error. That‘s why we fallback to the root container.
// Requesting a type that has been configured to use a "Per Request" lifetime scope, will result in a error
// in case of a background thread

if (HttpContext.Current == null)
return Container.Resolve<T>();

return DependencyResolver.Current.GetService<T>();
}
}
}

对于Resolve静态方法,用于Controller 之外的地方,用起来很方便。

2.创建一个IocConfig.cs 类文件,规范一点把这个文件创建在App_Start folder下,此类继承Autofac的Model,代码如下:

using Autofac;
using System.Reflection;
using Autofac.Integration.Mvc;
using Dlw.MiddleService.Sap.Interface;

using Module = Autofac.Module;

namespace Dlw.MiddleService.App_Start
{
public class IocConfig : Module
{
protected override void Load(ContainerBuilder builder)
{
// Register the mvc controllers.
builder.RegisterControllers(Assembly.GetExecutingAssembly());
// Register all interface
builder.RegisterAssemblyTypes(typeof(IStore).Assembly)
.Where(t => typeof(IStore).IsAssignableFrom(t))
.AsImplementedInterfaces().SingleInstance();
}
}
}

3.创建父类接口,Ioc注册接口的入口

namespace Dlw.MiddleService.Sap.Interface
{
public interface IStore
{
}
}

4.创建接口且继承Ioc注册入口 IStore,

namespace Dlw.MiddleService.Sap.Interface
{
public interface IRepository : IStore
{
string Test();
}
}

5.接口实现

namespace Dlw.MiddleService.Sap.Services
{
public class RepositoryImpl : IRepository
{
public string Test()
{
return "Hello World";
}
}
}

6. 在程序集中初始化Ioc且启动它进行工作

技术分享图片

7. MVC Controller 注入

技术分享图片

 

去吧少年,Ioc接口实例和MVC Controller 参数注入已经完成,Good Luck~

 

C# Ioc 接口注册实例以及注入MVC Controller

标签:void   middle   prot   exe   ret   文件   构造函数   接口   mod   

原文地址:https://www.cnblogs.com/Sitecore-develop/p/8425801.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!