標籤: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