开发者

httpcontext extension and IOC considerations

开发者 https://www.devze.com 2023-04-12 18:29 出处:网络
Hi created an extension method to control the lifecycle of an EF context.My code is below public static Entities GetCentralRepositoryContext(this HttpContext httpcontext)

Hi created an extension method to control the lifecycle of an EF context. My code is below

public static Entities GetCentralRepositoryContext(this HttpContext httpcontext) 
{
    if (HttpContext.Current.Items["context"] == null) 
    {
        HttpContext.Current.Items["context"] = new Entities(); 
    }

    return (Entities)HttpContext.Current.Items["context"];
}

I've created many layers in my solution as projects and have started to think about IOC. The above code sits in my BL layer project but for it to work I need to create a reference to my D开发者_运维知识库L layer as that's where the entities class resides. How can I remove the reference to my DL layer and inject into my extension method. Is this even possible?


The approach you are taking has several problems. First of all, static methods tend to be a problem for loose coupling, and you'll notice this quickly when trying to unit test your code. Besides this, your business layer has a dependency on System.Web, which makes your business layer technology specific, which will make it very hard to move part of the system to for instance a Windows Service, and again makes unit testing almost impossible.

Instead of doing this, start injecting your Entities class into the constructor of all types that need it. At the beginning of each request you can build up the dependency graph of services in your application, specific to that request. At that point you can determine that the Entities instance should have a lifetime of a web request.

This however, will start to get cumbersome to do without a DI framework. Or at least, a DI framework will make this much easier to do.

When you start writing unit tests, you'll find that it will be very hard when directly using the EF ObjectContext in your application. This article might give you some ideas how to abstract the ObjectContext behind a testable interface.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号