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

当弄一个小程序时,就忽略了使用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();
}
}
}
View Code

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

public interface IStore
{
}
}
View Code

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

public interface IRepository : IStore
{
string Test();
}
View Code

5.接口实现

public class RepositoryImpl : IRepository 
{
public string Test()
{
return "Hello World";
}
}
View Code

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

   public class Global : HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            WebContainer.Initialize(new IocConfig());
        }
    }
View Code

7. MVC Controller 注入

public class HomeController : Controller
    {
        public IRepository _store;
        public HomeController(IRepository store)
        {
            _store = store;
        }
        // GET: Home
        public ActionResult Index()
        {
            var result = _store.Test();
            return Content(result);
        }
    }
View Code

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

posted @ 2018-02-07 15:54  KevinMemory  阅读(910)  评论(0编辑  收藏  举报