Dependency registrar DependencyRegistrar : IDependencyRegistrar { Register services and interfaces Register(ContainerBuilder builder, ITypeFinder typeFinder, NopConfig config) { //注入ObjectContext builder.Register<IDbContext>(c => )).InstancePerLifetimeScope(); // 注入ef到仓储 builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope(); // 注入Service及接口 builder.RegisterAssemblyTypes(typeof(TestService).Assembly) .AsImplementedInterfaces() .InstancePerLifetimeScope(); //注入controllers //builder.RegisterControllers(typeFinder.GetAssemblies().ToArray()); 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); } } Order of this dependency registrar implementation Order { get { return 2; } } }
View Code3. 在启动时添加 EngineContext.Initialize(false),启动项目,报错了,因为winform不能执行,对方法做些调整,添加一个参数isForm表示是否是winform,默认为false。
Initializes a static instance of the Nop factory. [MethodImpl(MethodImplOptions.Synchronized)] public static IEngine Initialize(bool forceRecreate,bool isWinForm = false) { if (Singleton<IEngine>.Instance == null || forceRecreate) { Singleton<IEngine>.Instance = new NopEngine(); NopConfig config = null; if (!isWinForm) { config = ConfigurationManager.GetSection() as NopConfig; } else { appSettings = ConfigurationManager.AppSettings; foreach (var key in appSettings.AllKeys) { } } Singleton<IEngine>.Instance.Initialize(config); } return Singleton<IEngine>.Instance; }
View Code
static class Program { 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //Application.Run(new Form1()); //引擎上下文初始化 EngineContext.Initialize(false, true); Application.Run(EngineContext.Current.Resolve<Form1>()); } }
View Code4. From1中测试,成功调用了业务层的方法,这里我们并没有实例化ITestService,而是交给依赖注入自动实现。
Form1 : Form, IRegistrarForm { private ITestService _testService; public Form1( ITestService testService ) { InitializeComponent(); _testService = testService; //如果不注入form可以使用EngineContext.Current.Resolve<ITestService>(); 得到实例 } private void button1_Click(object sender, EventArgs e) { var tests = _testService.GetAllTests(); } }
View Code
至此,基于Nop的精简开发框架基本完成,如果你有兴趣,建议在github关注该项目 :https://github.com/dreling8/Nop.Framework,欢迎star给星星,你的支持是我的动力!