/// <summary> /// Dependency registrar /// </summary> public class DependencyRegistrar : IDependencyRegistrar { /// <summary> /// Register services and interfaces /// </summary> /// <param>Container builder</param> /// <param>Type finder</param> /// <param>Config</param> public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder, NopConfig config) { //注入ObjectContext builder.Register<IDbContext>(c => new NopObjectContext("test")).InstancePerLifetimeScope(); // 注入ef到仓储 builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope(); // 注入Service及接口 builder.RegisterAssemblyTypes(typeof(TestService).Assembly) .AsImplementedInterfaces() .InstancePerLifetimeScope(); //注入controllers builder.RegisterControllers(typeFinder.GetAssemblies().ToArray()); } /// <summary> /// Order of this dependency registrar implementation /// </summary> public int Order { get { return 2; } } }
3. 配置文件中添加数据库访问节点
复制代码 代码如下:
<add connectionString="Data Source=.;Initial Catalog=MyProject;Integrated Security=False;Persist Security Info=False;User ID=sa;Password=sa1234" providerName="System.Data.SqlClient" />
4. 应用启动时添加初始化引擎上下文
启动项目,这时NopEngine会报错,因为我们没有使用Nopconfig来配置项目,在RegisterDependencies方法中注释NopConfig的注入,同时在Initialize过程中将相关代码注释。这样就完成通过Autofac注入类到容器中。
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //引擎上下文初始化 EngineContext.Initialize(false); } }
//RegisterDependencies方法中注释NopConfig的注入 //builder.RegisterInstance(config).As<NopConfig>().SingleInstance(); public void Initialize(NopConfig config) { //register dependencies RegisterDependencies(config); //没有使用config,暂时注释 //register mapper configurations //RegisterMapperConfiguration(config); //startup tasks 没有启用任务,注释 //if (!config.IgnoreStartupTasks) //{ // RunStartupTasks(); //} }
5. 在controller添加测试代码。将service添加到HomeController,在构造函数中初始化。系统启动后会自动注入实例。通过断点我们看到,数据成功添加到了数据库。
public class HomeController : Controller { public ITestService _testService; public HomeController( ITestService testService ) { _testService = testService; } public ActionResult Index() { var entity = new TestEntity() { CreateDate = DateTime.Now, Description = "描述2", Name = "测试数据2" }; _testService.InsertTest(entity); var tests = _testService.GetAllTests(); return View(); }
五、扩展到Webapi、Winform、WPF
现在再添加一个winform项目,同样的步骤添加相关的代码。在Winform中我们也能使用业务的服务了。
1. 通过Nuget安装autofac,entityframework, 添加项目Libraries下的引用。
2. 添加依赖注册类,因为是winform项目,DependencyRegistrar这里需要做些调整,建议定义一个空接口IRegistrarForm,需要注入的Form实现IRegistrarForm。
/// <summary> /// Dependency registrar /// </summary> public class DependencyRegistrar : IDependencyRegistrar { /// <summary> /// Register services and interfaces /// </summary> /// <param>Container builder</param> /// <param>Type finder</param> /// <param>Config</param> public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder, NopConfig config) { //注入ObjectContext builder.Register<IDbContext>(c => new NopObjectContext("test")).InstancePerLifetimeScope(); // 注入ef到仓储 builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope(); // 注入Service及接口 builder.RegisterAssemblyTypes(typeof(TestService).Assembly) .AsImplementedInterfaces() .InstancePerLifetimeScope(); //注入controllers //builder.RegisterControllers(typeFinder.GetAssemblies().ToArray()); //注入forms var types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IRegistrarForm)))) .ToArray(); foreach (var formtype in types) { builder.RegisterAssemblyTypes(formtype.Assembly); } } /// <summary> /// Order of this dependency registrar implementation /// </summary> public int Order { get { return 2; } } }