MVC :: Are Repositories Automatically Disposed Of In C#?

Dec 6, 2010

Could someone explain what happens to the Repositories that are created when they are no longer needed? Are they automatically disposed of, or should we dispose of them manually?

Using EF4 as the DAL, to keep the program efficient I have been building repositories for the Model that abstract the data needed for specific views or actions. I have also used the Iinterface for the methods and call them in the Controller to pass them to the View. At some point the program needs to pass a behavior or request that requires the creation of a new repository and the process may repeat itself over and over again. What happens to the repositories that created for previous views, but are no longer needed? Should the dispose be written into each repository, or does garbage collection take care of this? How should this handled?

View 6 Replies

Similar Messages:

.net - Architecture With NHibernate And Repositories?

Apr 13, 2010

I've been reading up on MVC 2 and the recommended patterns, so far I've come to the conclusion (amongst much hair pulling and total confusion) that:

Model - Is just a basic data container Repository - Provides data access Service - Provides business logic and acts as an API to the Controller

The Controller talks to the Service, the Service talks to the Repository and Model. So for example, if I wanted to display a blog post page with its comments, I might do:

post = PostService.Get(id);
comments = PostService.GetComments(post); Or, would I do:

post = PostService.Get(id);
comments = post.Comments;

If so, where is this being set, from the repository? the problem there being its not lazy loaded.. that's not a huge problem but then say I wanted to list 10 posts with the first 2 comments for each, id have to load the posts then loop and load the comments which becomes messy.All of the example's use "InMemory" repository's for testing and say that including db stuff would be out of scope. But this leaves me with many blanks, so for a start can anyone comment on the above?

View 1 Replies

MVC :: Identity.Name Is Disposed In IIS7 Application Thread?

Jun 16, 2010

I don't know if it's IIS, ASP.NET or IIS7 related. I take a chance here, if you think I'm in the wrong forum, just tell me which one I should post to.

I have made the smallest demo project to illustrate my problem. You can download the sources


Visual Studio 2008, .NET 3.5, IIS7, Windows 7 Ultimate 32 bits. The IIS Website is configured
ONLY for Windows Authentication in an Integreated pipeline app pool (DefaultAppPool).

Here's the problem. I have an Asp.NET MVC 2 application. In an action, I start a thread. The View returns.

The thread is doing it's job... but it needs to access Thread.CurrentPrincipal.Identity.Name


The worker process of IIS7 stops. I have a window that says: "Visual Studio Just-In-Time Debugger An unhandled exception ('System.Object.DisposedException') occured in w3wp.exe [5524]"

I checked with the debugger and the Thread.CurrentPrincipal.Identity is valid, but the Name property is disposed.

If I put a long wait in the action before it returns the view, then the Thread can do it's job and the Identity.Name is not disposed. So I think the Name gets disposed when the view is returned.

For the sake of the discussion, here's the code that the thread runs (but you can also download the demo project. The link is on top of this post):


Here's the code that starts the thread


View 3 Replies

Traditional Repositories Vs Single UnitOfWork

Aug 17, 2010

I would like to start a debate on traditional repositories versus one built on the UnitOfWork pattern. In a traditional repository, we wrap inserts, updates and deletes in a transaction, but selects don't really need them. In addition, nhibernate configuration is typically done once per application due to BuildSessionFactory being rather expensive. We often have several repositories of this type (one per aggregate chain). We also need to have projected, ahead of time, exactly what kinds of queries we'll need in order to build the interfaces and concretes correctly. In a single UnitOfWork repository we have the ability to manage both the current session and transaction, perform several operations, and then commit any changes all at once. In such a repository we may opt to put our configuration in the constructor since (typically speaking) no more than one Action is called per request anyway, initializing it in the application doesn't seem like much of an overall gain in speed. I must admit, I'm very temped to use the UnitOfWork pattern, as the following code looks really nice to me:

Csharp Code:
using (IUnitOfWork worker = new UnitOfWork()){// session and transaction are now both set
// save changes to three itemsworker.SaveOrUpdate(item1);worker.SaveOrUpdate(item2);worker.SaveOrUpdate(item3);
// grab a fourth var item4 = worker.Criteria<Foo>().Add(Expression.Eq("title", title)).UniqueResult<Foo>();
// delete the fourthworker.Delete(item4);
// all pending operations are commited or rolled back as a single unit (if one fails, all are rolled back), and then disposed, along with the session}

My proposed UnitOfWork class is rather simple. It implements IDisposable where I use a try-catch-finally in Dispose() to attempt a tx.Commit(), doing a tx.Rollback on failure, and a cleaning everything up in the finally clause. It also exposes common things like SaveOrUpdate, Delete, GetAll, Get, and even a Critera<T>() for custom on-the-spot queries. So what are your thoughts on this? I'd really like to hear about your experience with this pattern.

View 4 Replies

Single Repository Or Multiple Repositories?

May 1, 2010

In a typical business application, a session is started and persisted across several pages. It is commited only when the transaction is complete. A good example of this is a tax preparation application. Once the session is started, it is persisted through session, cookies, or both. Nothing is written to file, or database, until the entire profile is complete and the refund/return is calculated. In such an ennvironment, is makes a great deal of sense to work with the structure imposed by domain driven design, and using a single repository to simple commit the session. However, there are times when this doesn't translate correctly, even when domain driven design is used.

An example of this is my forum project. While the entities themselves are good targets for domain driven design, I am not sure about the repositories. The basic structure is that a Category has many Forums, a Forum has many Threads, and a Thread has many posts. There are other things in there, but that's enough to describe what I want to get across. If a user has navigated to /Thread/Edit/42, and they have rights to edit it, all I am concerned about is fetching that record and displaying it. On postback, all I want is to be able to save it..................

View 2 Replies

C# - Are Repositories Useful Without Domain Driven Design?

Mar 9, 2011

Assuming my application did not warrant a full blown DDD setup, would Repositories still be useful? I like the way they shield from implementation details (such as use of Entity Framework) underneath. However Repositories tend to be tied to Aggregate Roots (the concept is still a holy grail to me) by definition.

I suppose the question could also be put as such: if I have a typical 3-tier application, with a business layer facade consisting of "logical grouping" classes based on functionality (rather than aggregate roots as in DDD) such as TradingManager and ContactsManager, would it make sense to also create "logical grouping" repositories. Or perhaps a Data Access Object, which I believe is like a Repository without the aggregate root requirement. Of course I will still have a Model (EF POCOs) that will be passed up and down between the layers.

Also, is what I just described would be considered as a Transaction Script approach? It's certainly not DDD, and not Active Record. I'm not even sure if Active Record exists with EF4 like it does with Nhibernate.

I am trying to understand how others structure n-layered applications when they do not follow DDD.

View 2 Replies

MVC :: Using EF4 Complex Types / Properties In Repositories?

Jan 13, 2011

Are there advantages in creating complex types in EF4 Entities and then use the complex properties in the repositories; instead of creating the aggregates in the the repository themselves? I.e. If the customer repository consists of properties of 3 entities: customers, addresses, email would it make sense to create a complex type consisting of the address and email properties, and add them as a complex property of the customer entity then just call the customer entity and the complex property in the repository, rather than just creating the repository class and aggregate the entities in the repository.What are there advantages or disadvantages in doing this in a MVC3 application?

View 10 Replies

MVC :: Multiple Repositories And Save DB Function

May 3, 2010

I have a few repositories in my project. All repositories inherit from an abstract interface repository containing the public datacontext variable and a Save function for the entire DB.

In my controllers I want to make changes to the the db and in one of my functions I'm working with two different repositories. Calling the Save function on each of the repositories I'm using can cause a situation in which one of the calls to Save succeeds and and the other fails resulting in a need of rolling back the changes of the Save function that failed.

What is the best way to work against multiple repositories and access to the DB to avoid such a situation?

View 7 Replies

C# - CA2000 Object 'comm' Is Not Disposed Along All Exception Paths?

Mar 8, 2011

I have a bunch of methods like so in my DAL in VS 2010. When I run the "new" Code Analysis option i get the message - Warning CA2000 object 'comm' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'comm' before all references to it are out of scope.

I understand I could use another using statement for the SQLCommand however if prefer to do it like I have with the Try/Finally block. My understanding is the Finally block executes last and does the cleanup.


View 1 Replies

C# - The ObjectContext Instance Has Been Disposed And Can No Longer Be Used For Operations That Require A Connection?

Mar 19, 2011

I have this view:

@model MatchGaming.Models.ProfileQuery
ViewBag.Title = "Index";


View 2 Replies

DataSource Controls :: SubmitChanges In Controller (mvc) Using Repositories (linq2sql)?

Jul 7, 2010

I'm got 2 model objects. Category and CategoryItem. I try to add a CategoryItem to Category in my Controller but It wont save to database, and I know why because I don't know how to call the submitChanges on the add while using repository, I dont got the DBContext right there is you know what I mean?.. here I will show you with code.


View 4 Replies

DataSource Controls :: Cannot Access A Disposed Object When Handling Foreign Key Relations?

May 15, 2010

i am currently working on an mvc 2 web app using LinqToSQL. I would like to handle a scenario where a user comes form a country and for this i have set the users - countries db relationship and in my user model i have a CountryId property.

I would like to display the country name on my users display view, so i tried fetching the country name like this: User.Country.Name, but an exception occurs that i cannot access a disposed object. I understand that this is caused by the way i handle my users repository and service.

This the repository users code:


This is the service users code (the repository is not class level property, but a local one that gets dipsosed immediately after calling it):


So, how could i handle such a scenario, where i would like the Country model to be also fetched in order to use it later? Should i convert the repository model a class level proprty in order not to get disposed?

View 3 Replies

C# - Leaving A BinaryReader Object Un-disposed In Order To Keep Request.InputStream Alive?

Feb 1, 2011

I have a couple methods to handle the saving of an image using Request.InputStream. I have two extensions that share the HttpContext. In one of my methods, I'm using a BinaryReader to read in the contents and do the processing. However, naturally, when disposing the BinaryReader, it closes off the InputStream property on Request. My SECOND method uses the same input stream to create a thumbnail.

Bascially, I need a way to keep the Request.InputStream property alive after disposing the reader in the first method. Is this possible? Here are my two methods. SaveImageStream() is called first, then GenerateThumbnail().


View 2 Replies

C# - .net Development Code Structure -Controllers, Services, Repositories & Contexts?

Dec 11, 2010

As a new developer I'm getting thoroughly confused by naming and structural conventions for developing c# code using best practice.I appreciate it's perhaps applicable to each domain I am developing for but I've seen the code of many different open source projects and there seems to be a common theme. The successful projects have well thought out structure for maintenance and extensibility.The terms context, service, repository and controllers are used often and I wondered if these are open to interpretation or is there a consensus or convention on what, where or how these get used.

In an e-commerce platform I've seen there are order services, order contexts, customer repositories and product controllers for example. What should they do based on these names? Does a controller do something different to a service? When should you use a context? Is there a convention for namespaces? It's mind boggling when you try and push from a spoon fed newbie developer and try to move on.What software/tools should I really be looking at to develop quality code? Unit Testing, Continous Integration, Resharper, Mocking tools, DOI Containers, nHibernate.

I'm not really aware of blogs/books that will help me push on from being a proficient web developer into someone who can develop extensible, quality and testable code. There are big gaps in authors assumptions. You are either a newbie or a software architect. I want to push from being a junior developer with a long term aim of being a software architect. I realise it's all about patterns and practices but where are the training materials? I work on my own so don't have the opportunity of learning from others.

View 2 Replies

DataSource Controls :: Get Child Properties Using Parent Object Error / Cannot Access A Disposed Object

Feb 17, 2010

On DBML I have two entities as Parent, Child. I am trying to assign Child class properites in a Parent.


I am getting the following Error:

Cannot access a disposed object.

Object name: 'DataContext accessed after Dispose.'.

View 2 Replies

C# - How To Avoid "The ObjectContext Instance Has Been Disposed " Error

Mar 30, 2011

I have a doubt concerning the Entity Framework in .NET.

I have a simple ASP .NET web page that has to insert some data in SQL Server with this function:


The good news is that the code that Insert function encapsulates I can move it to the place which is called. So my question is: What if there is a place in which I would be forced to call the function? How then I could avoid the error. Passing the parameter as reference (I tried and did not work).

View 2 Replies

ADO.NET :: Saving IQueryable In Cache Error "The ObjectContext Instance Has Been Disposed And Can No Longer Be Used For Operations That Require A Connection"

Oct 29, 2010

i want to save a IQueryable in cache like this:


However when i try to retreive it and use it i get this error: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

View 5 Replies

C# - Getting A Online Repositories And Project Management Tool For A Project?

Feb 16, 2010

Our team doing a project in & Mssql 2005.since our team member are distributed. we need a online tool for tracking project changes, and control access to our online code repositories.


View 4 Replies

.net - Id In Controls Automatically Changes?

Jan 11, 2011

I'm writing a bit of jquery to access a dropdown, but .net automatically changes the id by adding ctl00$...

Is there any way to stop it from changing it?

View 2 Replies

Update Table Automatically?

Dec 9, 2010

i am doing one web chat application.i show list of online user from db .some one user did not logout he exit. i want that time table automatically update the logout time (that partcular user ) .

View 4 Replies

Why Are The Links Changing Automatically

Oct 19, 2010

this.litBody.Text = body.ToString();

I'm using the above code to display database content on my website. The actual text on database is as follows.

<p>Forbury Investment Network (FIN) is a platform established to facilitate investment in early- and growth-stage companies in the technology sectors.</p>
<p>FIN was established by <a title="Clarkslegal" href="" target="_blank">Clarkslegal</a> and its subsidiary <a title="Forbury Environmental" href="" target="_blank">Forbury Environmental</a>, after 3 years of managing The EIC Environmental Investment Network.</p>

I have a test site and live site on the same server. Links work fine on test server. But when i look at the page on live server it the links are al wrong. www. is missin from both links and [URL] has become [URL]

View 2 Replies

Transfer Mails Automatically?

Sep 2, 2010

i have collection of mails with subject ,and i all the mails should be transfered to the realted dept as according to the subject in emails ?

View 10 Replies

How To Send Notifications Automatically

Jan 13, 2010

I want to send some notifications. Can this be done automatically? Say if I have coded a page that send notifications, but I have to go that page in the browser for the code to execute. Is it possible to code something that automatically sends notification even I dont' have to be there to execute the code?

View 5 Replies

How To Add News Automatically In Website With Rss

Nov 6, 2010

i want to do my site to receive news from other sites and display them.

View 11 Replies

How To Automatically Generate A Pdf File

Jan 25, 2011

I have a small web application based on 2010 that manages invoices.

After the invoice is saved, it should automatically generate a pdf file.

which of the following solutions would be fast and easy to incorporate?

Use Sql Server 2008 Reports
Use Crystal Reports 2008 and Crystal Reports 2008 for VS 2010
Use itextsharp to create the pdf file
Use XSLFO to create the pdf file

The point here is I dont know any of the above. Which one is easy and quick to learn and implement. Are there any other solution to achieve this functionality?

View 5 Replies

Copyrights 2005-15, All rights reserved