3、Controller的代码,HomeController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
namespace Demo.Controllers
{
public class HomeController : Controller
{
[Dependency]
public ITest Test { get; set; }
public ActionResult Index( )
{
ViewModel.Message = Test.GetString( );
return View( );
}
public ActionResult About( )
{
return View( );
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
namespace Demo.Controllers
{
public class HomeController : Controller
{
[Dependency]
public ITest Test { get; set; }
public ActionResult Index( )
{
ViewModel.Message = Test.GetString( );
return View( );
}
public ActionResult About( )
{
return View( );
}
}
}
4、ITest.cs代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo
{
public interface ITest
{
string GetString( );
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo
{
public interface ITest
{
string GetString( );
}
}
5、Test.cs代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Demo
{
public class Test:ITest
{
#region ITest 成员
public string GetString( )
{
return "Run demo!";
}
#endregion
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Demo
{
public class Test:ITest
{
#region ITest 成员
public string GetString( )
{
return "Run demo!";
}
#endregion
}
}
注意,这篇文章只适用于 ASP.NET MVC3 Beta 版,将来正式版出来了,未必采用这种方式来实现,毕竟对于依赖注入这块,从 MVC1 -> MVC3 Preview1 -> MVC3 Beta 一直都在变化
这里是采用Unity依赖注入框架的完整示例:下载(环境:VS2010 + MVC3 Beta + Unity)
这里是采用Ninject依赖注入框架的完整示例:下载(环境:VS2010 + MVC3 Beta + Ninject)