摘要:

下面的几篇文章介绍如何使用Ninject创建不同类型的应用系统。包括:

  • Windows Form应用系统
  • ASP.NET MVC应用系统
  • ASP.NET Web Form应用系统

尽管对于不同类型的应用系统,Ninject向应用组件注入依赖项的方式是相同的。但是根据不同应用系统架构不同,创建这些应用系统是不同的。一些新的框架例如ASP.NET MVC被设计成支持DI的,然而一些旧的框架例如ASP.NET是不支持所有DI模式。

前面已经介绍了Ninject提供的大多数功能,下面我们将在一个工程里应用这些功能。我们将实现一些应用,每一个应用都包含一个数据访问层,一个业务层,一个表现层,前面两层将在所有应用中共享。

程序下载

准备工作

1. 在网上下载Northwind数据库,并Restore或Attach到本地数据库。

2. 用Visual Studio 2015创建空解决方案Demo.Northwind。

3. 在解决方案Demo.Northwind里创建数据访问层工程:Demo.Northwind.Core。

在工程Demo.Northwind.Core内,用NuGet Manager添加引用EntityFramework和Ninject。

在工程Demo.Northwind.Core内添加如下文件/文件夹。

Customer.cs:

 namespace Demo.Northwind.Core.Model
{
public class Customer
{
public string CustomerID { get; set; } public string CompanyName { get; set; } public string City { get; set; } public string PostalCode { get; set; } public string Phone { get; set; }
}
}

ICustomerRepository.cs:

 using Demo.Northwind.Core.Model;
using System.Collections.Generic; namespace Demo.Northwind.Core.Interface
{
public interface ICustomerRepository
{
IEnumerable<Customer> GetAll(); Customer Get(string customerID); void Add(Customer customer);
}
}

NorthwindContext.cs:

 using Demo.Northwind.Core.Model;
using System.Data.Entity; namespace Demo.Northwind.Core.SqlDataAccess
{
public class NorthwindContext : DbContext
{
public NorthwindContext() { } public DbSet<Customer> Customers { get; set; }
}
}

SqlCustomerRepository.cs:

 using System.Collections.Generic;
using Demo.Northwind.Core.Interface;
using Demo.Northwind.Core.Model; namespace Demo.Northwind.Core.SqlDataAccess
{
public class SqlCustomerRepository : ICustomerRepository
{
private readonly NorthwindContext _context; public SqlCustomerRepository()
{
_context = new NorthwindContext();
} public void Add(Customer customer)
{
_context.Customers.Add(customer);
_context.SaveChanges();
} public Customer Get(string customerID)
{
return _context.Customers.Find(customerID);
} public IEnumerable<Customer> GetAll()
{
return _context.Customers;
}
}
}

创建工程Demo.Northwind.Winforms

Windows Forms是实现DI的一个最直接的应用系统类型。像Console应用程序一样,它不需要特别的Ninject配置。在Program类里的Main方法注册依赖项,框架里的组件例如Form类不需要一个无参数的构造函数,这使得实现构造函数注入变得很简单。

1. 在工程Demo.Northwind.Winforms内使用NutGet Manager添加如下引用:

2. 在工程Demo.Northwind.Winforms内添加到Demo.Northwind.Core的引用。

修改App.config,添加数据库连接字符串:

<connectionStrings>
<add name="NorthwindContext" providerName="System.Data.SqlClient" connectionString="Data Source=localhost;Initial Catalog=NORTHWND;Integrated Security=True" />
</connectionStrings>

3. 在MainForm里添加一个DataGrid控件,一个BindingSource控件。绑定DataGrid控件的数据源到BindingSource控件。

代码:

 using Demo.Northwind.Core.Interface;
using Demo.Northwind.Core.Model;
using System;
using System.Linq;
using System.Windows.Forms; namespace Demo.Northwind.Winforms
{
public partial class MainForm : Form
{
private readonly ICustomerRepository _repository; public MainForm(ICustomerRepository repository)
{
this._repository = repository;
InitializeComponent();
} private void MainForm_Load(object sender, EventArgs e)
{
LoadCustomers();
} private void LoadCustomers()
{
var customers = _repository.GetAll();
customerBindingSource.DataSource = customers.ToList<Customer>();
}
}
}

ICustomerRepository是这个类唯一的依赖项,在构造函数内引入和注入。

4. 既然MainForm的构造函数注入了一个ICustomerRepository对象,需要在Ninject中完成依赖注入,并使用kernel.Get<CustomerForm>()得到MainForm窗口对象,修改Program.cs:

 using System;
using System.Windows.Forms;
using Ninject;
using Ninject.Extensions.Conventions; namespace Demo.Northwind.Winforms
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false); using (var kernel = new StandardKernel())
{
kernel.Bind(x => x.FromAssembliesMatching("Demo.Northwind.*")
.SelectAllClasses()
.BindAllInterfaces()); var mainForm = kernel.Get<MainForm>();
Application.Run(mainForm);
}
}
}
}

5. 如果要在MainForm窗口上加一个“Create”按钮,点击按钮打开一个CustomerForm窗口用来添加新Customer并保存到数据库。CustomerForm窗口类也应该在构造函数中注入一个ICustomerRepository对象。

新建Windows Form:CustomerForm。

代码:

 using Demo.Northwind.Core.Interface;
using Demo.Northwind.Core.Model;
using System;
using System.Windows.Forms; namespace Demo.Northwind.Winforms
{
public partial class CustomerForm : Form
{
private readonly ICustomerRepository repository; public CustomerForm(ICustomerRepository repository)
{
this.repository = repository;
InitializeComponent();
customerBindingSource.Add(new Customer());
} private void saveButton_Click(object sender, EventArgs e)
{
customerBindingSource.EndEdit();
var customer = customerBindingSource.Current as Customer;
repository.Add(customer);
this.DialogResult = DialogResult.OK;
} private void closeButton_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}
}
}

6. 在MainForm.cs中添加Create按钮事件:createButton_Click:

         private void createButton_Click(object sender, EventArgs e)
{ }

问题来了,CustomerForm窗口类只有一个注入ICustomerRepository对象的构造函数,不能使用new无参数的构造函数创建CustomerForm窗口类对象,也不能在MainForm窗口类里再新创建一个kernal对象,使用Get方法得到CustomerForm对象。

因此,我们怎么办呢?这个时候应该使用Ninject动态工厂。多亏了Ninject工厂功能,我们只需要简单地定义如下的接口:

 using System.Windows.Forms;

 namespace Demo.Northwind.Winforms
{
public interface IFormFactory
{
T Create<T>() where T : Form;
}
}

在MainForm类里添加IFormFactory对象:

private readonly IFormFactory _formFactory;

修改MainForm类createButton_Click事件:

         private void createButton_Click(object sender, EventArgs e)
{
var customerForm = _formFactory.Create<CustomerForm>();
if (customerForm.ShowDialog(this) == DialogResult.OK)
{
LoadCustomers();
}
}

修改MainForm类构造函数,添加IFormFactory对象注入:

         public MainForm(ICustomerRepository repository, IFormFactory formFactory)
{
this._repository = repository;
this._formFactory = formFactory;
InitializeComponent();
}

最后是在Program类的Main方法里添加注册我们的动态工厂服务:

             kernel.Bind(x => x.FromThisAssembly()
.SelectAllInterfaces()
.EndingWith("Factory")
.BindToFactory()
.Configure(c => c.InSingletonScope()));

运行系统,测试系统运行情况。

Ninject之旅之十二:Ninject在Windows Form程序上的应用(附程序下载)的更多相关文章

  1. Ninject之旅之十:Ninject自定义提供者

    摘要 提供者是特殊的工厂类,Ninject使用它来实例化解析类型.任何时候我们绑定一个服务类型到一个组件,我们都隐式地关联那个服务类型到一个可以实例化那个组件的提供者.这个隐藏的提供者被称为Stand ...

  2. JAVA之旅(十二)——Thread,run和start的特点,线程运行状态,获取线程对象和名称,多线程实例演示,使用Runnable接口

    JAVA之旅(十二)--Thread,run和start的特点,线程运行状态,获取线程对象和名称,多线程实例演示,使用Runnable接口 开始挑战一些难度了,线程和I/O方面的操作了,继续坚持 一. ...

  3. Ninject之旅之十一:Ninject动态工厂(附程序下载)

    摘要 如果我们已经知道了一个类所有的依赖项,在我们只需要依赖项的一个实例的场景中,在类的构造函数中引入一系列的依赖项是容易的.但是有些情况,我们需要在一个类里创建依赖项的多个实例,这时候Ninject ...

  4. Ninject之旅之十三:Ninject在ASP.NET MVC程序上的应用(附程序下载)

    摘要: 在Windows客户端程序(WPF和Windows Forms)中使用Ninject和在控制台应用程序中使用Ninject没什么不同.在这些应用程序里我们不需要某些配置用来安装Ninject, ...

  5. Ninject之旅之十四:Ninject在ASP.NET Web Form程序上的应用(附程序下载)

    摘要 ASP.NET Web Forms没有像MVC那样的可扩展性,也不可能使它创建UI页面支持没有构造函数的的激活方式.这个Web Forms应用程序的的局限性阻止了它使用构造函数注入模式,但是仍能 ...

  6. Ninject之旅之九:Ninject上下文绑定(附程序下载)

    摘要 既然在插件模型里,每一个服务类型可以被映射到多个实现,绑定方法不用决定要返回哪个实现.因为kernel应该返回所有的实现.然而,上下文绑定是多个绑定场景,在这个场景里,kernel需要根据给定的 ...

  7. Sql Server之旅——第十二站 sqltext的参数化处理

    说到sql的参数化处理,我也是醉了,因为sql引擎真的是一个无比强大的系统,我们平时做系统的时候都会加上缓存,我想如果没有缓存,就不会有什么 大网站能跑的起来,而且大公司一般会在一个东西上做的比较用心 ...

  8. Python学习之旅(十二)

    Python基础知识(11):高级特性 一.分片(切片) 通过索引来获取一定范围内的元素 #字符串 s="Alice" s[0:4:2] 结果: 'Ai' #列表 l=[1,2,3 ...

  9. 前端编程提高之旅(十二)----position置入值应用

    这次内推项目用到的遮罩及其页面下方button都涉及一个概念position置入值得概念.效果图例如以下: 一个元素position属性不是默认值static.那么该元素被称为定位元素. 定位的元素生 ...

随机推荐

  1. UVA 11149 Power of Matrix

    矩阵快速幂. 读入A矩阵之后,马上对A矩阵每一个元素%10,否则会WA..... #include<cstdio> #include<cstring> #include< ...

  2. ZOJ 3537 Cake

    区间DP. 首先求凸包判断是否为凸多边形. 如果是凸多边形:假设现在要切割连续的一段点,最外面两个一定是要切一刀的,内部怎么切达到最优解就是求子区间最优解,因此可以区间DP. #include< ...

  3. github 更新fork分支

    在github上开发代码的时候我们习惯的是fork一个分支,然后修改再往主分支push request,这样就可以保证多人开发, 但是随着时间的推移,自己fork的版本和主分支的版本差异越来越大; 这 ...

  4. IOS数据库FMDB增、删、改、查的使用【原创】

    http://blog.it985.com/13588.html IOS数据库FMDB增.删.改.查的使用[原创] FMDB是一个XCODE的中一个轻量级的数据库,用于将网络资源存储在本地.所以,FM ...

  5. iOS子线程更新UI的两种方法

    http://blog.csdn.net/libaineu2004/article/details/45368427 方法1:performSelectorOnMainThread[self perf ...

  6. HCSR04超声波传感器驱动

    HC_SR04是一款使用较为广泛的超声波测距模块,模块图如下 该模块具有四个引脚,分别为VCC GND TRIG ECHO,其中VCC GND为供电脚 TRIG为测距触发引脚,ECHO为测距输入引脚 ...

  7. 获取url参数和时间格式化

    1. 获取url参数: var url = request("url"); //获取url参数 function request(paras) { //decodeURI() 函数 ...

  8. SQL数据库文件修复/用友/金蝶/管家婆/速达/思讯数据库恢复 硬盘恢复

    硬盘的故障情况可以分为以下几类: 1.控制电路故障 大部分外电路的问题是电源芯片或主轴驱动芯片烧坏引起的,由于硬盘电路板质量问题.设计缺陷.市电波动.突然断电.芯片老化或者散热不良.静电等原因造成芯片 ...

  9. django的HTTPREQUEST对象

    Django使用request和response对象 当请求一张页面时,Django把请求的metadata数据包装成一个HttpRequest对象,然后Django加载合适的view方法,把这个Ht ...

  10. 【转】java调用存储过程和函数

    一.概述 如果想要执行存储过程,我们应该使用 CallableStatement 接口. CallableStatement 接口继承自PreparedStatement 接口.所以CallableS ...