摘要:

下面的几篇文章介绍如何使用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. JS中Exception处理

    程序开发中,编程人员经常要面对的是如何编写代码来响应错误事件的发生,即例外处理(exception handlers).如果例外处理代码设计得周全,那么最终呈现给用户的就将是一个友好的界面.否则,就会 ...

  2. function $(id){ return document.getElementById(id); }导致所有的js不能用解决办法。。。。

    function $(id){ return document.getElementById(id); } document.getElementById(id) 是获得id这个元素的. 相当于定义了 ...

  3. wex5 实战 苹果左滑删除与长按编辑

    用了多年苹果,习惯了苹果的左滑删除与长按编辑,特别是短信什么的,很多安卓界面也采用了类似方式. 我的想法突如其来,用wex5也设计一个这样的功能,可以吗? 那句广告词,没有什么不可能. 呵呵. 一   ...

  4. window环境变量

    首先Window中有很多乱七八糟的路径变量之类的,归类下来有几类,主要是为了我们分清楚概念,以免搞的糊涂了. 1. Window系统的环境变量:顾名思义,就是系统级别的变量,或者利用我们编程的角度来讲 ...

  5. 图片拉伸iOS

    - (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight: (NSInteger)topCa ...

  6. Java Base64、AES、SHA1、MD5加密算法(转载)

    package com.example.decript; import java.io.UnsupportedEncodingException; import java.security.Inval ...

  7. HMC5883L地磁传感器驱动

    霍尼韦尔 HMC5883L 是一种表面贴装的高集成模块,并带有数字接口的弱磁传感器芯片,应用于低成本罗盘和磁场检测领域.HMC5883L 包括最先进的高分辨率 HMC118X 系列磁阻传感器,并附带霍 ...

  8. 史上最坑的证书报错解决方法:Code=3000 "未找到应用程序的“aps-environment”的权利字符串"

    在ios注册远程通知获取设备令牌token的时候 // 注册远程通知获取设备令牌 toKen [[ UIApplication sharedApplication ] registerForRemot ...

  9. JQuery基础知识(2)

    JQuery基础知识(2) JQuery滑动效果 1. JQuery slideDown(); 语法: $(selector).slideDown(speed,callback); 可选的 speed ...

  10. 2786: [JSOI]Word Query电子字典

    2786: [JSOI]Word Query电子字典 Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 3  Solved: 3[Submit][Statu ...