Entity Framework ObjectContext With Dependency Injection?

Jan 6, 2011

Here's what I want to do:

UI layer: An ASP.NET webforms website.

BLL: Business logic layer which calls the repositories on DAL.

DAL: .EDMX file (Entity Model) and ObjectContext with Repository classes which abstract the CRUD operations for each entity.

Entities: The POCO Entities. Persistence Ignorant. Generated by Microsoft's ADO.Net POCO Entity Generator.

I'd like to create an obejctcontext per HttpContext in my repositories to prevent performance/thread [un]safety issues.

public MyDBEntities ctx
string ocKey = "ctx_" + HttpContext.Current.GetHashCode().ToString("x");
if (!HttpContext.Current.Items.Contains(ocKey))
HttpContext.Current.Items.Add(ocKey, new MyDBEntities ());
return HttpContext.Current.Items[ocKey] as MyDBEntities ;

I don't want to access HttpContext in my DAL (Where the repositories are located). But I have to somehow pass HttpContext to DAL. based on the answer to my question here, I have to use IoC pattern.

View 1 Replies


C# - What Dependency Injection Framework With WebForms

Nov 27, 2010

I have been looking at learning dependency injections (i think i have now grasped the basics) and am looking to implement it into a webform application. My question is, what dependency injection framework should i use for a webforms project, or is it a question of what works best for you?

I Have currently looked at Spring.Net, Ninject, Unity and StructureMap, i tend to have no preference in the configuration, whether its XML or fluent interfaces. However is XML configuration becoming less favourable?

Most of the information i come across relates to dependency injection whilst in a MVC environment. And have also read that some frameworks such as Structure Map only work with webforms using version 2.0 or earlier. So the kind of things i need to consider are whether webforms will be continuous support, and the ease of configuration for someone relatively new to the pattern.

View 1 Replies View Related

ADO.NET :: Entities Framework 4.0 Dependency Injection, WebForms?

Feb 21, 2011

I am sort of new to Entities Framework however I have successfully built a complete CMS website with the Entities Framework 4.0 in MVC 2.0 following the design patterns and examples laid out in nerddinner and MusicStore.

I am now building another application in ASP.NET webforms however would still like to flex the ORM capabilities of ADO.Net Entity Framework 4.0 however found that it seems like I am always forced to use Entity ObjectDataSource to bind to a GridView etc...

I know I might sound silly to some however I need a few pointers on creating this ASP.NET web application to use Entity Framework and use something like the design pattern of Dependency Injection etc... and still able to bind to GridViews programmatically in code behind.

I like the seperation of using a ntiers design but also would like to have full code control and not be forced to use ObjectDataSources in my aspx page.

View 3 Replies View Related

Entity Framework - ObjectContext?

Mar 3, 2011

im working with a proyect made in ASP.Net using Webforms. Im using Entity Framework to save data on Microsoft SQL.

My question is:

Is posible to use a Static class to keep the ObjectContext of EF live and put/get entities NOT saved inside the ObjectContext??

I wan to create an Object, then added with AddObject on the ObjectContext, But NOT to do the Savechanges. All this in one webform An then, in other webform, access to the ObjectContext and Get the Object added

View 3 Replies View Related

.net - Entity Framework ObjectContext Re-usage?

Apr 27, 2010

I'm learning EF now and have a question regarding the ObjectContext: Should I create instance of ObjectContext for every query (function) when I access the database? Or it's better to create it once (singleton) and reuse it? Before EF I was using enterprise library data access block and created instance of dataacess for DataAccess function...

View 5 Replies View Related

MVC :: Dependency Injection, IoC, Policy Injection

Nov 14, 2009

What are they, why are they used and how can I use them in MVC? What sense do they make?

What is the difference between IoC and Dependency Injection? For me they look the same at the moment.

What are good tools for these? I already did some searching and came up with entlib, ninject, windsor castle.

View 3 Replies View Related

MVC :: Dependency Injection Using IValidationDictionary

Oct 28, 2009

I'm currently using the method provided here


to do my validation. I was wondering how one would go about using dependency injection with that design.It looks like the ProductController Needs a IProductService object and the IProductService Object needs the ProductControllers ModelState.

When using structuremap i get a stackoverflow error because of the circular dependency. I'm assuming it's due to the circular dependency.

View 2 Replies View Related

C# : Dependency Injection And Roles?

Jul 20, 2010

I have a page using an injected BLL service: a simple service returning a set of objects with a function like this:

public IMyService { List<Foo> All(); }

There is a default implementation for normal users.Now, i need that users in administrative role can view more objects, with another implementation of the service.Where can i configure my page to use the second implementation?

My first solution is to put the dependency to the IUnityContainer in the page, and use it to resolve the dependency:

public IUnityContainer Container { get; set;}

Page_Init(..) [code].....

it's a ServiceLocator and it's neither scalable neither testable.

View 2 Replies View Related

C# - .NET Module Dependency Injection?

Jan 3, 2011

During the design of a new generic authentication framework for some of our products, I have come across an architectural issue I cannot seem to find a good solution for.I have tried to simplify the problem in order to easily explain it.

The library has two classes:

Manager Is responsible for storing currently authenticated users.Module It is the responsibility for the module to validate each request according to security policies. The Module must ask the manager to determine whether a user is currently authenticated.

Now the manager is supplied an implementation of an interface which allows the manager to load users from a repository. The specific implementation is not contained in this library. Because of this, I cannot directly instantiate an instance of the repository within the library.

I have no way of modifying properties or supplying arguments for the module constructor. So my question is this, how can I give the module a reference to an instance of the Manager?

namespace Demo
public interface IRepository

View 4 Replies View Related

Dependency Injection / How To Use It In WebForms Appliction

Apr 2, 2010

as i've read Ninject is the best one so how to use it and why i cannot see good examples.

Lately i have begun learning MVC and as i've seen every one use DI in the MVC, i have a couple doesn question but i will ask a few lol...

1. Why use and what is going to do for me?

2. How to use it in WebForms Appliction ?

3. IoC is the same if not what is it and what's it doing?

4. I want to use a Ninject FrameWork 2.0 but i cannot find good examples for WebForm App.

View 4 Replies View Related

MVC :: Dependency Injection With Custom Constraint

Jul 20, 2010

I have a custom constraint that queries a value against a repository. Is it possible to replicate the dependency injection available to controller constructors?

View 1 Replies View Related

MVC :: ModelBinder For Dependency Injection On ViewModels?

Jan 25, 2011

This project is pretty far away and I'm not in the position to go make changes all over the place (If I could, deleting the lot would be what I'd do!)

I want to create a modelbinder that would resolve any dependencies my View Models might have (using StructureMap).

It should not require me to implement a specific interface (so many developers, so many interfaces..I rather keep things clean) and hopefully not require one to go register each model binder individually (Now I'm asking too much,taking the first requirment
in consideration).

Probably will get it right tonight, but figured I'd ask.

View 3 Replies View Related

C# - Dependency Injection - Colloquial Explanation

Apr 8, 2010

Recently I was asked to express the DI in colloquial explanation.

I answered :

1)I am going to a hotel.I ordered food.The hotel management asks me to clean the plates and
clean the tables.So here i am a client,I am responsible for managing the service (Instantiating,executing,disposing).But DI decouples such tasks so the service consumer no need not worry about controlling the life cycle of the service.

2)He also asked is there any microsoft API follows DI ?.I answered (This was my guess) In WCF you can create a Proxy using ChannelFactory that controls the life time of your factory.

for item (1) he said only 10% is correct

for item(2) he said that is factory pattern not dependency injection.

Actually what went wrong in my explanation (apart from my bad English) ? What is the real answers for those?

View 3 Replies View Related

.net - What's The Point Of Dependency Injection Frameworks

Aug 12, 2010

I am sure that I am somewhat lost in this area... my understanding is that Dependency Injection means initializing something that is required by a class..so for instance. If my controller is going to need a service and I want to be able to test it then I should define two Constructor methods for it... so, my question is.

public class CompaniesController : Controller
private ICompaniesService _service;
public CompaniesController()

View 6 Replies View Related

MVC :: Dependency Injection / The Role Of A 'Model'?

May 27, 2010

My general understanding of the MVC pattern is that the model is reponsible for persisting itself. Though I also see other opionions that models should be dumb data objects and that controllers should persist them via a data access layer.

Per http://en.wikipedia.org/wiki/Model_view_controller: "Many applications use a persistent storage mechanism such as a database to store data. MVC does not specifically mention the data access layer because it is understood to be underneath or encapsulated by the model." Though it does also mention "Models are not data access objects."

Per http://www.asp.net/mvc/tutorials/asp-net-mvc-overview--cs, "Models. Model objects are the parts of the application that implement the logic for the applications data domain. Often, model objects retrieve and store model state in a database. For example, a Product object might retrieve information from a database, operate on it, and then write updated information back to a Products table in SQL Server."

First, am I misguided in believing that models should persist themselves? Or, is this just a matter of opinion?

Second, if I follow the pattern where controllers manage the persistence of the model, I find it fairly easy to use dependency injection to inject a data access component into my controller using a custom controller factory (implementing the IControllerFactory
interface). If I follow the pattern where my model saves itself, I'd want to inject my data access component into the model. Is there a way to provide a custom factory for models? Otherwise, I don't think using DI with models is possible.

View 5 Replies View Related

Dependency Injection And Code Maintainability?

Oct 30, 2010

I am working on a (vb.net/asp.net) project that is using interfaces to provide dependency injection. But to me, it feels like the maintainability of the code has been killed. When I want to read through the code, I can't simply jump to the code of a related class that is used. All I see are the interfaces, and so I have to hunt through the project to figure out what classes are doing the implementation. This really hurts my productivity.

Yes, I know I now can implement the interfaces with a wide variety of replacement classes. But for example, I know I'm not changing my data source any time soon--there is no need for me to enable the ability to swap that out. All of this dependency injection seems like overkill to me (in fact, the only real reason it is there is to support mock classes for unit testing). I've actually read several places that state DI is actually better for maintainability. But that assumes you already know where everything is and you know which class you need to update. Finding out where to look is the part that is killing me. So, my question is: Is there a better way to traverse through the code? Is there a better way to make the code more maintainable? Are we just doing it wrong? Or is this par for the course?

View 2 Replies View Related

Implement StructureMap To Handle My Dependency Injection

Oct 26, 2009

there's a logical problem in trying to implement StructureMap to handle my dependancy injection. Take a look a the code below and see if you can assist me in how to configure the registry.

Csharp Code:
public CategoryController(ICategoryService categoryService){this._categoryService = categoryService;}
Csharp Code:
public CategoryService(IStateWrapper stateWrapper, ICategoryRepository categoryRepository){this._stateWrapper = stateWrapper;this._categoryRepository = categoryRepository;}
Csharp Code:
public StateWrapper(ModelStateDictionary state){
this._state = state;}
Csharp Code:
public CategoryRepository(DataProvider dataProvider){this._DataProvider = dataProvider;}

Ok, so I create an empty registry...

Csharp Code:
public class KokonoeRegistry : Registry{
public KokonoeRegistry(){this.Scan(scanner =>{scanner.TheCallingAssembly();scanner.WithDefaultConventions();});}}

And an IoC object...

Csharp Code:.........................

View 24 Replies View Related

MVC :: Consume WCF Service In Application Using Dependency Injection?

Nov 11, 2010

private IGetData _getData;

View 2 Replies View Related

Architecture :: Dependency Injection Learning Hurdle?

Jul 21, 2010

i'm just starting with asp.net mvc and specifically the repository pattern. I've read as much as i can but there doesn't appear to be a great article on dependency injection (ioc) as lots of people are doing it different. I found one article

http://weblogs.asp.net/cibrax/archive/2008/08/21/dependency-injection-made-easy-for-the-asp-net-mvc.aspx and it looks simple for setting up my data context (IDataContext) against a controller. However i have my own custom DataAnnotation attribute which
makes sure that a person's name is unique:

public class UniqueUserNameAttribute : ValidationAttribute
public override bool IsValid(object value)
string str = (string)value;

if (string.IsNullOrEmpty(str))
return true;

using (IDataContext context = new LinqToSqlDataContext())
return context.Repository<User>().Find(u => u.UserName == str).Count() == 0;

As you can see there's a hard coded dependency on my linq to sql data context. This means i can't test but i also can't see what else i can do.I'd really appreciate it if someone could point me in the right direction and recommend the best dependency injection library to use (such as StructureMap, Unity, Autofac...).

View 1 Replies View Related

MVC :: Dependency Injection In A LayoutPage Base Type?

Dec 17, 2010

I've created a base page type that derives from WebViewPage<T>.

I'm using a StructureMap implementation of IDependencyResolver to inject dependencies using setting injection

i.e.public ISomeService SomeService {get;set;}

Whilst this works fine on a normal view page, my services are not injected on a Layout page.

Are the base types for a standard view page and layout page the same?

If I call IDependencyResolver directly in the base page type then it works fine but I would prefer not to do this.

View 2 Replies View Related

Dependency Injection Gotchas / Looking For List Of Links?

Aug 16, 2010

Does anyone have a list of link(s) on the www for a good list of DI gotchas?I have been trying to inject controls using DI, in an asp.net webforms app and found that on recursive build up that ViewState is lost.

Also would be helpful a list of articles where the developer needs to be aware to gotchas before taking teh big step in implementing IoC/DI in the app.

View 1 Replies View Related

Dependency Injection With Custom Membership Provider?

May 2, 2010

I have an ASP.NET MVC web application that implements a custom membership provider. The custom membership provider takes a UserRepository to its constructor that provides an interface between the membership provider and NHibernate. The UserRepository is provided by the Ninject IoC container.

Obviously, however, this doesn't work when the provider is instantiated by .NET: the parameterless constructor does not have a UserRepository and cannot create one (the UserRepository requires an NHibernate session be passed to its constructor), which then means that the provider cannot access its data store. How can I resolve my object dependency?

It's probably worth noting that this is an existing application that has been retrofitted with Ninject. Previously I used parameterless constructors that were able to create their required dependencies in conjunction with the parametered constructors to assist unit testing.

View 3 Replies View Related

MVC :: Html Helpers / User Controls Dependency Injection?

May 12, 2010

I've just started wokring with Asp.Net mvc and i relay love it. One thing I don't know how to do it yet is:

If I want to develope a new user control (e. g. PeoplePicker) how I get the data? I don't want to use allways ajax requests, some controls should be initialized when the page is loaded. So I could use the Html Helpers and create own extension. So far this is exactly what i want and it's working. But now to the real problem. I can't use dependency injection in extension methods (I'm using spring.net, but the problem should be in all di frameworks).

So which approche is the most common to use this problem? Must I realy pass in the data from my controller? But then the controller must know how my user controls works, I don't want that!

View 6 Replies View Related

C# - Best Way To Integrate Dependency Injection Using Unity When Static Methods Are Used?

Mar 8, 2010

Im faced with an impending upgrade to an ASP.NET site and I am thinking of introducing DI using Unity. I have researched the ASP.NET DI side of things and have 2 options (Global.asax or IHttpModule). Im happy to use either. As always, there is a legacy object model in place that I would like to upgrade/change. I would like to go down the route of Constructor injection (passing in the DAO) however, each object has a mix of static and instance methods that both currently call into the DB using SqlCommand objects themselves. I want this removed to provide DB independence, therefore can anyone suggest the best way to do the DI in this case? Im open to drastic changes if they are needed.

public class ExampleClass
public ExampleClass(int test)
TestProperty = test;
public int TestProperty {get; set;}
public int Save()
// Call DB and Save


View 1 Replies View Related

Dependency Injection - Use Rhino Service Bus On Website With Ninject?

Aug 6, 2010

I will like to add Rhino Service Bus to my ASP.NET web application but using Ninject as the DI Container. So far all examples I keep seeing use Castle Windsor which I don't want to use since we already use Ninject.Are there any tutorials out there which show how to add Rhino Service Bus to an ASP.NET web application without a direct dependency on Castle Windsor (e.g. using Ninject)?

View 1 Replies View Related

MVC :: Custom Authenticate Attribute With Constructor (Dependency) Injection?

Sep 7, 2010

I have a [BeastAuthenticate] attribute on my controller. The following code works fine but I would like to use Contructor (Dependency) Injection with Unity. The problem is that the attribute will run the contructor with no parameters. terfaces ITMSLogger and IADGroups are setup to use Dependency Injection with TMSLogger and ADGroups respectively. The following code works fine but doesn't use dependency injection for class ADGroups.


I tried the following but I'm getting an error ("Object reference is required...") with "this (adGroups).


View 2 Replies View Related

How To Pass Unit Of Work Container Into Constructor Of Repository Using Dependency Injection

Jul 23, 2010

how to complete my implementation of the Repository pattern in an ASP.NET web application.

At the moment, I have a repository interface per domain class defining methods for e.g. loading and saving instances of that class.

Each repository interface is implemented by a class which does the NHibernate stuff. Castle Windsor sorts out the DI of the class into the interface according to web.config. An example of an implemented class is provided below:


As pointed out in a previous thread, the repository class needs to accept an unit of work container (i.e. ISession) rather than instantiating it in every method.

I anticipate that the unit of work container will be created by each aspx page when needed (for example, in a property).

How do I then specify that this unit of work container instance is to be passed into the constructor of StoredWillRepository when Windsor is creating it for me?

View 4 Replies View Related

Exporting Entity Framework 4 Data Model To Entity Framework 3.5?

Oct 25, 2010

Is there a way to export a EF 4.0 Data Model to EF 3.5?

I looked around and found that we are not able to access EF 4.0 from a ASP.Net 3.5 project here: [URL]

Our project is the 1st to go to .Net 4.0 using Entity Framework and we (the team) were wondering if there was a way for the other projects that "might" need to access our data that are still using the .Net 3.5 framework.

View 1 Replies View Related

ADO.NET :: Entity Framework With Stored Procedure Versus Entity Framework Without Stored Procedures

Nov 2, 2010

I am new to entity framework , it is really very good , but I want to know what is the difference between using entity framework with stored procedure or without stored procedure , which one the faster and what is the benefits for using stored procedures with entity framework.

View 1 Replies View Related

Entity Framework -Update Entity When Another Entity Is Updated

Jun 30, 2010

I have an EDM, it includes the entities extension and history. My goal is to use history to keep track of all the changes made to extension entity. For example, if extension with ID 223 has its property 'Name_Display' changed - I want the history entity to record this.

I'm using ASP.NET with VB.NET. Where in my code do I put the hook to say, "update the history entity" and what should that hook look like?

View 1 Replies View Related

Copyrights 2005-15 www.BigResource.com, All rights reserved