- Overview
- What DotNetAge do for MVC with DI
- Which DotNetAge modules and services support DI?
- How to use DI in DotNetAge
Before you start
This document is introduction to the DotNetAge development core concept from high level - Dependency injection. This document describes what MVC service locators are extended by DotNetAge and how DotNetAge using DI to implement a plug-able architecture for MVC.
If you are already read the following articles maybe help to understand this document:
- Inversion of Control Containers and the Dependency Injection pattern by Martin Fowler
- Microsoft Unity 2.0
- "ASP.NET MVC 3 Service Location" - by Brad Wilson
Overview
DotNetAge 2.1 is a revolutionary release, it is largely abandoned in the past from the infrastructure. DotNetAge use the Microsoft Unity 2.0 to extend the ASP.NET MVC3 service locators to build a plugable architecture. Developers can use DI anywhere in DotNetAge!
Why dependency injection?
The purposes of using dependency injection pattern are:
- Reduce coupling between modules
- High scalability-Services and modules are all plug-able in DotNetAge.
- Effectively manage the life-cycle of objects and enhance performance
- Easy to write test.
What DotNetAge do for MVC with DI
DotNetAge implement a service container for Mvc, DI is available in all service locations in Mvc 3 including Controllers,Filters,Actions.
To learn more about Mvc3 service locations please refer : "ASP.NET MVC 3 Service Location"
Which DotNetAge modules and services support DI?
The answer is : All of them!
Modules and services of DotNetAge are base on DI pattern such as Repositories(IRepository,IUnitOfWork), Open search engine, Notification service, Syndication, Exporting , Installation service and ect.As long as you are developed using DotNetAge, DI will be ubiquitous
How to use DI in DotNetAge
In DotNetAge your Mvc application will support constructor injection, property injection, and method call injection.
Notes: For more about unity configuration please refer:The Unity Configuration Schema
Inject to Controllers
This example shows how to inject the IPubService to the ArticleController and call the NewPost method in Action.
Step1: Inject and use the interface
public partial class ArticleController : Controller
{
private IPubService srv;
//Inject the IPubService interface
public ArticleController(IPubService service)
{
srv = service;
}
public ActionResult Create(Article article)
{
if (ModelState.IsValid)
{
...
//Invoke srv.NewArticle method
srv.NewPost(article, isAdmin);
return Redirect(new ArticleWrapper(article).PermaLink);
}
return View(article);
}
}
- Controller no need to know how to instantiate the IPubService. The IPubService instance is created and injected by DotNetAge in run time.
- In this way developer can very easy to Mock a service to Controller in testing code.
[TestMethod]
public void Should_Create_Article()
{
var service = new Mock();
service.Setup(srv=>srv.NewPost(It.IsAny(),true)).Returns(new Article());
var httpContext=Faker.FakeHttpContext();
var controller=new ArticleController(service.Object);
controller.ControllerContext = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller);
var result = controller.Create(new Article());
//Do some verify
...
}
Step2:Register IPubService to unity.config
Open unity.config to register type mappings and object instances.
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
...
<alias alias="IPubService" type="DNA.Mvc.Publishing.IPubService,DNA.Mvc.Publishing.Services" />
<alias alias="PubService" type="DNA.Mvc.Publishing.PubService,DNA.Mvc.Publishing.Services" />
<assembly name="DNA.Mvc.Publishing.Services" />
<container>
<register type="IPubService" mapTo="PubService">
<lifetime type="PerWebRequest" />
<constructor>
<param name="pubContext" type="IPubContext" />
<param name="dbContext" type="IDataContext" />
constructor>
register>
container>
unity>
In unity.config we:
- Register the alias names for IPubService and PubService.
- Add an assembly for locate.
- Map IPubService interface to PubSerivce class.
- Specified the PubService constructor parameters.
- Specified the PubService using the PreWebRequest lifetime manager.
PreWebRequest lifetime manager - Specified the typed object returns from Unity container has the same life cycle as a http request.
References
Inject to Filters
As we know a filter can implement one of more of the following interfaces: IActionFilter, IResultFilter, IExceptionFilter, and IAuthorizationFilter. DotNetAge extend the filter providers to support DI for MVC3. So all filters in DotNetAge is inject-able.
One thing to note is the filters can not support constructor injection.
Example: In this example we define a new Filter and inject the IDataConetxt (The interface use to access the DotNetAge core objects) , we use DependencyAttribute to specify which property should be injected.
using Microsoft.Practices.Unity;
public class MyFilter:ActionFilterAttribute
{
[Dependency]
public IDataContext DataContext{get;set;}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//Get the web object from database
var web=DataContext.Webs.GetByName("home");
//Do something here
...
}
}
Reference: Registering Injected Parameter and Property Values
IDataContext interface is use access the DotNetAge core objects it was already registered in unity.config.
The following code is the IDataContext registered elements in unity.config:
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias alias="IDataContext" type="DNA.Mvc.IDataContext,DNA.Mvc.Data" />
<alias alias="DataContext" type="DNA.Mvc.Data.DataContext,DNA.Mvc.UI" />
<container>
<register type="IDataContext" mapTo="DataContext">
<lifetime type="PerWebRequest" />
register>
container>
unity>
DependencyResolver
In design time developers also can use the System.Web.Mvc.DependencyResolver to resolve an instance for the interface. The other way is use the WebSiteContext.GetService() and WebSiteContext.GetServices().
For example:
public interface IMyInterface
{
//Define this interface
}
public class MyClass:IMyInterface
{
//Implement the interface.
}
public class MyController:Controller
{
public Action DoSomething()
{
//Resolve the IMyInterface instance.
var myclass=DependencyResolver.Current.GetService();
...
// Or
var myclass=WebSiteContext.GetService();
}
}
The registered interfaces
There are many interface registered in unity.config by DotNetAge. Developers can resolve the instances of this interfaces directly.
The following table list all registered public interfaces:
Interface | Description |
---|---|
IDataContext | DotNetAge core object access interface. Provides the repositories to handle Webs,WebPages,Widgets,WidgetDescriptors,WidgetTemplates,PermissionSets,Permissions,OpenIDs,Themes,Solutions, PrivateMessages POCO objects. |
IPubContext | Publishing objects access interface,Provide repositories for Category, Article and Comment. |
IForumContext | Community objects access interface. Provide repositories for Forums, Threads and Posts. |
IGlobalFilter | Register a global DI filter. |
IAppInitializer | The interface use to execute the initialize task on app start. |
IWebResourceService | Defines the methods to manipulate the managed web resources. |
INotificationService | Defines the methods to subscribe,unsubscribe and send messages to subscribers. |
ISubscriptionRepository | Defines the repository methods to access subscription objects. |
ISubscriptionSender | Defines the send method to various kinds of subscription source. |
IFormsAuthentication | Defines forms authentication service methods. |
IMembershipService | Defines membership service methods. |
ILogRepository | Defines the repository methods for access log objects. |
IWebStatRepository | Defines the repository methods for analyze log data. |
IPubService | Defines the publishing service methods. |
ISpammerRepository | Defines the repository methods to access the spammer objects. |
Exporter | Defines a base exporter class to packing the data to package. |
EventObserver | Defines the observer base class for handling DotNetAge events. |
InstallerBase | Defines the installer base class to deploy the data/files to DotNetAge. |
SiteMapGeneratorBase | Defines methods to generate the sitemap data and add to global sitemap file. |
OpenSearchProvider | Defines the search provider base class,inherit this class could extend more search source. |
RssItemsGeneratorBase | rss data generator base class. |
AtomEntriesGeneratorBase | atom generator base class. |
-
-
Читает(1262)
-
Trackback(0)
-
Постоянная ссылка
Комментарии (0)