C# Ioc 接口注册实例以及注入MVC Controller
2021-02-15 19:23
当弄一个小程序时,就忽略了使用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();
Container = builder.Build();
DependencyResolver.SetResolver(new Autofac.Integration.Mvc.AutofacDependencyResolver(Container));
}
public static T Resolve
{
// 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
return DependencyResolver.Current.GetService
}
}
}
对于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~
上一篇:抽奖系统 WPF
文章标题:C# Ioc 接口注册实例以及注入MVC Controller
文章链接:http://soscw.com/index.php/essay/55779.html