摘要:

下面的几篇文章介绍如何使用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. [Unity AssetBundle]Asset资源处理

    什么是AssetBundle 在很多类型游戏的制作过程中,开发者都会考虑一个非常重要的问题,即如何在游戏运行过程中对资源进行动态的下载和加载.因此,Unity引擎引入了AssetBundle这一技术来 ...

  2. MODBUS协议详解

    MODBUS是一个工业上通信常用的通讯协议,一般在PLC上面用的比较多,主要是定义了一种数据传输的规范,比如数据发给谁,数据是干嘛的,数据错没错,接收到数据的从机告诉我数据有没有接受到等. 传输的方式 ...

  3. spring中依赖注入与aop讲解

    一.依赖注入 这个属于IOC依赖注入,也叫控制反转,IOC是说类的实例由容器产生,而不是我们用new的方式创建实例,控制端发生了改变所以叫控制反转. 1 2 3 4 5 6 7 8 9 10 11 1 ...

  4. ios 添加PCH文件

  5. 23、手把手教你Extjs5(二十三)模块Form的自定义的设计[2]

    在本节中将要加入各种类型的字段,在加入字段的时候由于可以一行加入多个字段,因此层次结构又多了一层fieldcontainer.form里面的主要层次结构如下: form -- fieldSet -- ...

  6. Laravel 用户验证Auth::attempt fail的问题

    1.在laravel项目中,当使用Auth::attempt()用于用户验证时,Auth::attempt()会把密码通过Hash进行转换,变成一串不知啥的长字符,如果你在数据库里事先设置了明文的密码 ...

  7. js 设置url 参数值

    //设置url中参数值 function setParam(param,value){ var query = location.search.substring(1); var p = new Re ...

  8. 使用 System.Transactions 进行事物管理

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...

  9. bzoj1070————2016——3——14

    传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=1070: 题目概括: Description 同一时刻有N位车主带着他们的爱车来到了汽车维修中 ...

  10. React Native 之 HelloWorld

    1. 切换目录 输入之前要切换到要保存的目录 2. 修改下载源 cd ~/ vim .npmrc 添加 registry = https://registry.npm.taobao.org 3. 在终 ...