2012-10-25 41 views
2

我正在评估单个项目ASP.NET Web窗体应用程序上下文中的Highway.Data.EntityFramework.Unity程序包。在Global.asax中添加静态引用到服务层可以吗?

我想要轻松访问我的服务层。这里是全球的相关部分:

public class Global : HttpApplication 
{ 
    private static readonly IUnityContainer Container = new UnityContainer(); 

    public static IEmployeeService Service { get; private set; } 

    protected void Application_Start(object sender, EventArgs e) 
    { 
     Container.BuildHighway(); 
     Container.RegisterType<IMappingConfiguration, EntityMapping>(); 
     Container.RegisterType<IEmployeeService, EmployeeService>(
      new PerRequestLifetimeManager()); 
     Container.RegisterType<IRepository, Repository>(
      new PerRequestLifetimeManager()); 
     Container.RegisterType<IDataContext, DataContext>(
      new PerRequestLifetimeManager(), 
      new InjectionConstructor("DataContext", new EntityMapping())); 

     Service = Container.Resolve<IEmployeeService>(); 
    } 
} 

在我的客户,我可以像这样访问:

this.Employees.DataSource = this.service.GetEmployees(); 
this.Employees.DataBind(); 

工作正常,但我之前只是因为它似乎并没有采取这种方法好的...好吧,是吗?如果不是,我该怎么办?

[编辑]请求清晰。

服务:

public class EmployeeService : IEmployeeService 
{ 
    private readonly IRepository repository; 

    public EmployeeService(IRepository repository) 
    { 
     this.repository = repository; 
    } 

    public IEnumerable<Employee> GetEmployees() 
    { 
     return this.repository.Find(
      new AllEmployeesQuery()) 
      .ToList() 
      .Select(ObjectMapper.Map<EmployeeEntity, Employee>); 
    } 
} 

AllEmployeesQuery是一个规范。业务对象由AutoMapper映射到EF实体,反之亦然。

感谢, 理查德

+0

如何通过this.service.GetEmployees()访问它; ??不应该是Global.Service.GetEmployees() – kabaros

+0

没错,Global.Service.GetEmployees() – Richard

回答

0

你要避免使用此方法像瘟疫。不要在应用程序级别共享数据库连接或资源;它会导致糟糕的表现和微妙的错误。

我发现的最佳模型是为每个请求创建一个连接并将其存储在当前请求中,以使该连接可用于请求生命周期中可能发生的任何其他调用。

以下代码是我们数据层的静态属性。默认行为是在第一次获取连接并将其存储在请求中,随后访问此属性将返回以前创建的实例。在没有HttpContext的情况下,该属性还使用户能够明确地覆盖这个。

protected static dataLayer DataContext 
{ 
    get 
    { 
     if (HttpContext.Current == null) 
     { 
      if (StaticContext == null) 
       StaticContext = new dataLayer(); 

      return StaticContext; 
     } 

     if (HttpContext.Current.Items["dataLayer"] == null) 
      HttpContext.Current.Items["dataLayer"]= new dataLayer(); 

     return (dataLayer)HttpContext.Current.Items["dataLayer"]; 
    } 
} 
+0

你从哪里得到OP试图“共享数据库连接或资源”? “IEmployeeService”意味着共享资源并不十分清楚。 –

+0

“为每个请求创建连接并将其存储在当前请求中” - 您何时释放请求所持有的资源?请不要说GC。 –

+0

数据/服务层实现无与伦比,并有一个终结器。当请求完成时,它不在上下文中。 – Heather

相关问题