تنظبمات Global.asax
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.F ilters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
initStructureMap();
}
private static void initStructureMap()
{
ObjectFactory.Container.GetInstance<IUnitOfWork>() .ForceDatabaseInitialize();
ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());
}
protected void Application_EndRequest(object sender, EventArgs e)
{
HttpContextLifecycle.DisposeAndClearAll();
}
}
public class StructureMapControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
return ObjectFactory.Container.GetInstance(controllerType ) as Controller;
}
}
}
نمونه ApplicationDataContext
public class DataContext : DbContext, IUnitOfWork {
public DataContext():base("DefaultConnection")
{
}
public DbSet<Product> Product { get; set; }
public DbSet<ProductGroup> ProductGroup { get; set; }
public override int SaveChanges()
{
return base.SaveChanges();
}
public void RejectChanges()
{
foreach (var entry in this.ChangeTracker.Entries())
{
switch (entry.State)
{
case EntityState.Modified:
entry.State = EntityState.Unchanged;
break;
case EntityState.Added:
entry.State = EntityState.Detached;
break;
}
}
}
public void ForceDatabaseInitialize()
{
Database.Initialize(true);
}
#region IUnitOfWork Members
public new IDbSet<TEntity> Set<TEntity>() where TEntity : class
{
return base.Set<TEntity>();
}
#endregion
}
نمونه ObjectFactoty.cs
public static class ObjectFactory {
private static readonly Lazy<Container> ContainerBuilder =
new Lazy<Container>(DefaultContainer, LazyThreadSafetyMode.ExecutionAndPublication);
public static IContainer Container
{
get { return ContainerBuilder.Value; }
}
private static Container DefaultContainer()
{
var container = new Container(x =>
{
x.For<IUnitOfWork>().HybridHttpOrThreadLocalScoped ().Use(() => new DataContext());
//x.For<DataContext>().HybridHttpOrThreadLocalScoped ().Use(context => (DataContext)context.GetInstance<IUnitOfWork>());
//x.For<DbContext>().HybridHttpOrThreadLocalScoped() .Use(context => (DataContext)context.GetInstance<IUnitOfWork>());
x.For<IProductService>().Use<ProductService>();
x.For<IProductGroupService>().Use<ProductGroupServ ice>();
});
return container;
}
}