此类继承Autofac的Model

时间:2022-01-08 06:08:47

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

MVC integration requires the Autofac.Mvc5 NuGet package.

文档:#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且启动它进行事情

此类继承Autofac的Model

7. MVC Controller 注入

此类继承Autofac的Model

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