Extending the ASP.net MVC three-tier framework and using StructureMap to implement dependency Injection 1-model layer _ Practical Tips

Source: Internet
Author: User
Tags httpcontext

This article will show you how to add a service and repository layer and use StructureMap to inject the service layer into the controller and inject the repository into the service layer. Service layer is mainly our business logic layer, this layer does not deal with the underlying database, and database dealing with the repository data persistence layer. This article minimizes the coupling of the Controller,service,repository three layer by using StructureMap dependency injection.

This system uses Northwind open source data and uses EntityFramework5.0 to implement object mapping for the database.

Before we start, let's take a look at the shape of the frame structure, we will be around this screenshot to unfold.

--> first, let's look at what's inside this project Tystudiodemo.models

This contains our entityframwork edmx file, the collection of objects that the Northwind database table maps. The ado.net Entity Data model was built here without using the default to generate a bunch of. tt files, but using the old form. The implementation of the method is first set up by the default program data model, set up a good data model after the deletion. tt file. Then open the. edmx file, right-click the blank to select Properties, the screenshot below, which only needs to modify the code Generation strategy (Chinese translation does not know what, the first on the) value, the default is None, We modify to default and then save. edmx



You should have noticed that there is a TYEntities.cs file in the project, which is the key to implementing transaction (transaction) in our system.
We use the static and [ThreadStatic] properties to ensure that the tyentities (ObjectContext) that a thread gets is always the same, which solves the problem of the transaction transaction. No explanations please read the comments in the following code in detail.

Copy Code code as follows:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using System.Web;

Namespace Tystudiodemo.models
{
public partial class Tyentities
{
#region Fields

Define index name
Const string Contextkey = "Tyentities";

Static fields marked as ThreadStaticAttribute are not shared between threads.
Each thread of execution has a separate field instance and sets and gets the value of the field independently. If you access the field in a different thread, the field will contain a different value.
[ThreadStatic]
private static tyentities _current;

#endregion

#region Properties

public bool disposed {get; set;}

<summary>
When the system works under HttpContext, the delay home will be used in the technology to return a tyentities (ObjectContext) If no HttpContext will return null
///
No matter where you use tyentities, you need to call the Tyentities.cleanup () method at the end of the request
The best way is to Tyentities.cleanup () into the Global.asax.cs file.
void Application_EndRequest (object sender, EventArgs e)
/// {
TYStudioDemo.Models.TYEntities.Cleanup ();
/// }
</summary>
private static Tyentities Forwebrequest
{
Get
{
var context = HttpContext.Current;

Check if HttpContext exists
If (context!= null)
{
Try to get tyentities from the context
var result = context. Items[contextkey] as tyentities;

if (result = = null)
{
Create a new DataContext and save it in the context
result = new Tyentities ();
Context. Items[contextkey] = result;
}

return result;
}

return null;
}
}

<summary>
This is a public property used to get Tyentities (ObjectContext)
///
If you get tyentities through HttpContext, the same no matter where you use tyentities, you need to call the Tyentities.cleanup () method at the end of the request
///
If you do not get tyentities through HttpContext, you must call the Tyentities.cleanup () method after the end of the use to clean up ObjectContext.
///
One thing to note is that regardless of the way you get tyentities, we must manually clean and dispose tyentities (ObjectContext).
So be sure not to use Tyentities (ObjectContext) in a using block.
</summary>
public static Tyentities Current
{
Get
{
Get DataContext from HttpContext
var result = Tyentities.forwebrequest;

if (Result!= null)
return result;

Try to get the tyentities of the current activity
if (_current = null)
_current = new Tyentities ();

return _current;
}
}

<summary>
Cleanup End tyentities (ObjectContext)
</summary>
public static void Cleanup ()
{
if (httpcontext.current!= null)
{
var result = Httpcontext.current.items[contextkey] as tyentities;

if (Result!= null)
Result. Dispose ();

Httpcontext.current.items[contextkey] = null;
}
else if (_current!= null)
{
_current. Dispose ();
_current = null;
}
}


protected override void Dispose (bool disposing)
{
BOOL disposed = disposed;
disposed = true;

if (!disposed)
Cleanup ();

Base. Dispose (disposing);
}

#endregion
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.