Why am I getting "Row Not Found Or Changed" Error Here? - c#

I've googled around the "Row Not Found or Changed" error for some time, and I'm just unable to see how the error is being caused in my application.
I have a facade class, called DataAccess, which wraps multiple repositories, and gets passed around my application. Every controller has a dependency upon DataAccess, so I've hooked it up to unity to pass out as required.
Data Access looks roughly like this, in truncated/abstracted form:
public class DataAccess : IDataAccess
{
private MyDataContext DataContext = new MyDataContext();
public Repository1 Repo1 = new Repository1();
public Repository2 Repo2 = new Repository2();
public DataAccess()
{
Repo1.DataContext = DataContext;
Repo2.DataContext = DataContext;
}
}
Then each controller has a dependency upon IDataAccess like so:
public class MyControllerBase
{
[Dependency]
IDataAccess DataAccess { get; set; }
}
Unity hands these out according to what appears to be normal configuration, registering types in Global.asax, hooking controllers up to a factory, resolving with unity. Furthermore, I've registered it with a PerThreadLifetimeManager(), which I am unsure whether is correct.
For the most part this works great - however the problem can be reproduced by:
Go to Edit action and post an edit (redirects to Index)
Go back into the Edit action and attempt to post another edit, OR, go into Delete action and attempt to post a Delete on the same item
This throws the "Row Not Found or Changed" error. Each action (Edit and Delete) calls SubmitChanges() on the DataContext. So I'm not quite sure what's going on here. If anyone has any ideas they would be extremely well received.
Cheers,
Tim.

I suspect the per-thread lifetime is not appropriate here - ASP.NET reuses threads across requests, and that would result in reusing your old contexts across multiple requests, possibly leaving them in odd states.
You have two choices:
If you only call container.resolve on the controller, then you could use the built-in PerResolveLifetimeManager instead. This would give you a single DataAccess object per controller resolve.
You could grab one of the many PerRequestLifetimeManager implementations and get a new DataAccess object per HttpRequest.
Either way will, I suspect, get you out of the issues you've got currently.

Related

How to clean up instances created by SimpleInjector during verification?

As a part of creating my SimpleInjector container, I've followed recommended practices and called container.Verify() to check that my type registrations make sense.
This works well and has caught a number of errors that I've made - but it also creates debris that lingers around afterwards that I'd like to clean up.
One of my classes is a singleton event hub that's used to route messages between other transient components; these other components accept the event hub in their constructor, create a subscription to receive the messages they're interested in receiving, then Dispose() the subscription when they're finished.
The call to container.Verify() creates one of each kind of object, resulting in a number of these otherwise transient instances lingering around because the event hub still knows about their subscriptions.
At the moment I've worked around the problem by manually terminating all subscriptions immediately after the Verify() call, before the application starts up. However, this feels like a problem that must be already solved, though I haven't been able to find an answer in the docs, here on Stack Overflow, or by searching.
Perhaps using a scoped lifestyle is the solution? They didn't seem relevant because I'm building a WPF application, but if I knew the answer I wouldn't be asking here!
Update, 12 Jan - As requested by #steven, here's some code to demonstrate my issue.
I tried (and failed) to demonstrate the issue with something that was both compilable and short enough to share inline; instead I'm showing some code excerpts from the actual project. If you want to see the whole thing, the WordTutor project is on GitHub.
At the core of my application I have a singleton IReduxStore<T> which both encapsulates application state and acts as a kind of event hub. Other classes subscribe to the store in order to be proactively notified when the application state changes.
Here is IReduxStore<T>, pared down to the essentials:
// IReduxStore.cs
public interface IReduxStore<T>
{
T State { get; }
void Dispatch(IReduxMessage message);
IDisposable SubscribeToReference<V>(
Func<T, V?> referenceReader,
Action<V?> whenChanged)
where V : class, IEquatable<V>?;
}
Subscriptions implement IDisposable as a convenient and idiomatic way for deterministic cleanup when the subscription is no longer required.
The store is registered as a singleton, bound to a specific type of state:
// Program.cs
container.RegisterSingleton<
IReduxStore<WordTutorApplication>,
ReduxStore<WordTutorApplication>>();
The implementation of IReduxStore<T> stores all the subscriptions:
private readonly HashSet<ReduxSubscription<T>> _subscriptions
= new HashSet<ReduxSubscription<T>>();
They're removed from the HashSet when disposed.
Many of my ViewModels accept IReduxStore<WordTutorApplication> to their constructors so they can subscribe to updates:
// VocabularyBrowserViewModel.cs
public sealed class VocabularyBrowserViewModel : ViewModelBase
{
private readonly IReduxStore<WordTutorApplication> _store;
private readonly IDisposable _screenSubscription;
private readonly IDisposable _vocabularySubscription;
public VocabularyBrowserViewModel(IReduxStore<WordTutorApplication> store)
{
_store = store ?? throw new ArgumentNullException(nameof(store));
// ... elided ...
_screenSubscription = _store.SubscribeToReference(
app => app.CurrentScreen as VocabularyBrowserScreen,
RefreshFromScreen);
_vocabularySubscription = _store.SubscribeToReference(
app => app.VocabularySet,
RefreshFromVocabularySet);
// ... elided ...
}
// ... elided ...
}
ViewModels are registered as transient because each window needs a unique instance:
// Program.cs
var desktopAssembly = typeof(WordTutorWindow).Assembly;
container.Collection.Register<ViewModelBase>(desktopAssembly);
The ViewModels release their subscriptions proactively when they are no longer needed:
// VocabularyBrowserViewModel.cs
private void RefreshFromScreen(VocabularyBrowserScreen? screen)
{
if (screen == null)
{
_screenSubscription.Dispose();
_vocabularySubscription.Dispose();
return;
}
Selection = screen.Selection;
Modified = screen.Modified;
}
When Verify() is called on the SimpleInjector container, an exemplar of every object is created, including the singleton IReduxStore<T>. The transient viewmodels (such as VocabularyBrowserViewModel shown above) are also created, but those instances remain live because their subscriptions are still held by the store.
I tried implementing IDisposable on the ViewModels, but because their lifestyle is transient, the only effect was to generate an additional warning when Verify() was called.
Update II, 12 Jan:
The workaround I have at the moment is to manually clear all the subscriptions as a part of application startup, after the container has been successfully initialized:
var store = (ReduxStore<WordTutorApplication>)
container.GetInstance<IReduxStore<WordTutorApplication>>();
store.ClearSubscriptions();
This feels like a nasty hack. First it needs to explicitly cast to the implementation type, then it calls a method that otherwise wouldn't need to exist at all.
Try setting EnableAutoVerification to false in Simple Injector 5.0 (https://simpleinjector.org/ReferenceLibrary/html/P_SimpleInjector_ContainerOptions_EnableAutoVerification.htm)

Can I resolve a scoped instance from inside a singleton instance in asp.net 5

I've been using a trick for a while to help with maintaining an audit trail. In or before the controller, I create a User which is bound in some way to the request. I can use DI to create most of my application as singletons and I can just inject a Func<User> wherever I think I need User information. I get the per-request User from the Func and can easily add audit information to everything.
This keeps my domain classes User agnostic and lets my DI container act as a User management system.
Now I'm using asp.net 5 and I'm having trouble doing the same thing. Honestly I've never been sure I should be able to do this, but I've gotten used to it.
I'm trying to do something like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddScoped<IUser, User>();
services.AddSingleton<IDependantOnUser, DependantOnUser>
services.AddScoped<Func<IUser>(c => c.GetRequiredService<IUser>);
}
Then in or before my controller I create and populate the user instance.
public class ValuesController : Controller
{
public ValuesController(Func<User> userFunc)
{
user = userFunc();
// hydrate user instance as needed
}
}
Then finally, I should have access to the user instance in my singleton object.
public class DependantOnUser : IDependantOnUser
{
public DependantOnUser(Func<User> userFunc)
{
user = userFunc();
// I want this to be the same instance as that generated by the controller
}
}
But I can't get this to work. Before asp.net 5, I've been using Autofac to achieve this, but haven't had any luck there. I've tried playing around with transient/scoped/singleton a bit with no luck. I've even tried resolving my own IServiceProvider and using it directly instead of just generating a user with c => c.GetRequiredService<IUser>
Everything I do seems to be working with the wrong IServiceProvider instance. Is there a way resolve an instance from a different ServiceProvider? Any other suggestions would also be helpful.
Before you suggest I just register everything using AddScoped(), some of the objects between my presentation and persistence layers work a lot better as singletons.
Also I would prefer not to just pass User information as a parameter to every method in my domain (we record it with nearly every CRUD operation and pass it with most external calls we make)
I believe that it is antipattern to inject scope depedency to singleton one, please refer to Captive Dependencies
Autofac Captive Dependencies

How should I communicate between ViewModels?

I am using MVVM Light and have used the packaged messenger system to communicate between view models, however I have hit a bit of a dilemma! Basically when a user clicks on a customer record the corresponding view is opened and with it the CustomerViewModel is instantiated. At this point the CustomerViewModel requires the selected customers ID from the previous view model (ViewAllCustomersViewModel) so that it can get selected customers info which the view binds to (still following?). So initially my thought was too send that ID in a message from the ViewAllCustomersViewModel (where the customer to be viewed is selected) to the CustomerViewModel... HOWEVER, the CustomerViewModel is not instantiated to be able to receive the message until the view is loaded (at which point the message has already been broadcast)!
So, what would be the best way to solve this issue? So far I have considered the CustomerViewModel sending a request to the ViewAllCustomersViewModel once it has been instantiated (basically saying "I am ready to receive the message"), and then the ViewAllCustomersViewModel sending the ID back to the CustomerViewModel... but is this a necessary approach to solve this? It seems a bit ugly to me!
Otherwise, I was thinking is there another way to communicate which can account for the issue I am having? But then isn't this the whole point of the messaging system... to be able to communicate between view models? OR can I force the view model to be instantiated on start up? If so, how would that affect the ViewModelLocator?
I hope I have outlined the issue clearly, I have used fictional view model names for the purpose of the explanation... and please feel free to edit or suggest any additional information that you would like me to add!
Did you try to communicate via your model? I was not able to read your topic until the end but this is how I communicate between ViewModels.
Both View Models have the instance of session.
public ViewModel1(ISession session)
{
_session = session;
}
public ViewModel2(ISession session)
{
_session = session;
}
This way, when you test your application in BDD (behavior driven development), you can test your application without the view. The glue is the model.
As you can see on this picture, you should be able to test your application without the view.
I came across the same situation where two view model is communicating each other. I have used Microsoft PRISM framework to publish and Subscribe.
In your case CustomerViewModel is parent View and ViewAllCustomersViewModel is child view.
Download prism framework "Microsoft.Practices.Prism.PubSubEvents.dll" from https://www.nuget.org/packages/Prism.PubSubEvents/
Add prism reference to your project "Microsoft.Practices.Prism.PubSubEvents.dll"
Create some custom class which is used for communication modem.
class Notifications : PubSubEvent<string>
{
}
Create IEventAggregator eventAggregator singleton instance for your project and initialize it.
public sealed class SessionInfo
{
public IEventAggregator eventHanlder;
private SessionInfo (){
}
private static SessionInfo _instance = null;
public static SessionInfo Instance{
get{
lock (lockObj){
if (_instance == null) {
_instance = new SessionInfo ();
_instance.eventHanlder= new EventAggregator();
}
}
return _instance;
}
}
}
Go to Popover model (ViewAllCustomersViwModel) button events handling and below codes in it.Now it has been published.
In ViewAllCustomersViwModel.cs:
public void OnSelectedItem(Item item)
{
SessionInfo.Instance.eventHanlder.GetEvent<Notification>().Publish(item.id);
}
These event aggregator has to be subscribe where it is needed. So add below code on your Parent View model (CustomerViewModel)
CustomerViewModel.cs
public class CustomerViewModel
{
public CustomerViewModel()
{
SessionInfo.Instance.eventHanlder.GetEvent<Notifications>().Subscribe(OnReceivedNotification);
}
//Handling the notification
public void OnReceivedNotification(string itemId)
{
Debug.WriteLine("Item Id is :" + itemId);
}
}
For more information:
https://sites.google.com/site/greateindiaclub/mobil-apps/windows8/communicationbetweenviewmodelsinwindows8mvvmpattern
I believe that standard way is to pass it through View.
Depending on how you instantiate your views, it could be DependencyProperty to bind in XAML, constructor parameter, or anything else.
Then View passes it to it's ViewModel (pushes it to VM, not the way around: ViewModel should not be aware of View). This way you get a standalone closed component (your View), and external code does not know about it's internal implementation (which is ViewModel).
In XAML it can be something like
<ListBox x:Name="customers" />
<CustomerView Customer="{Binding SelectedItem, ElementName=customers}" />
And then in CustomerPropertyChanged handler you push value to the ViewModel.
Personally, I used to use the MVVM-Light Messenger, but found I had way to many messages flying around, and I didn't like the feeling of using a "magical" messenger. What I did is outlined as the answer to the following link
Best Way to Pass Data to new ViewModel when it is initiated.
Now I warn you, I answered my own question, and nobody verfied it as good or bad practice, however it works for my situation and has elimnated the need for MVVM-Light Messenger. Because my program uses multiple threads in my implementation I changed all the entries in the repository to Dictionarys with the CurrentThread.ManagedThreadId as the Key.
So far I have considered the CustomerViewModel sending a request to
the ViewAllCustomersViewModel once it has been instantiated (basically
saying "I am ready to receive the message"), and then the
ViewAllCustomersViewModel sending the ID back to the
CustomerViewModel...
I would continue with this idea. It keeps the Views, ViewModels and Models all separate and unknowing of the others unlike other answers. Not to say other answers are wrong, or even bad, your option can be defined one or any of: personal preference, team convention, long-term MVVM goal of replacing components/modules, and complexity/ease of coding.
A side-effect to your idea I quoted above, which I prefer, is that you can request at any time as you've already set it up. So if you change when to perform that request very easily, or if you need to request updates, you use the same communication architecture in place.
Lastly, I prefer it because if you change your models or views or viewmodels - you keep the same core concept of communicating information between components.

How do I spawn child thread processes when using shared entities injected via Unity?

I have an ASP.Net MVC3 solution running a batch import process which fetches data from a web-service. For each row/loop, the process needs to send up to four emails. I'd like to fire these emails off in background threads so that the main thread doesn't have to wait for the emails to be sent. The child email thread needs to update the database audit table on email send completion or failure.
The issue I'm having is that I use Unity to inject the IEmailer class into my main process thread, which also assigns the 'main process thread' datacontext into the emailer class. So I get errors when the datacontext has already been closed when the emailer tries to update the audit table if the main loop has already finished (a plausible scenario).
How do I tell Unity to assign a new datacontext to my new emailer threads, or how do I tell my emailer class to use a different unity container (configured with Transient datacontext, I guess?)?
Here's my stripped down code. (I realise I could just instantiate a 'new MyDataContext()' inside the emailer but there is definitely a better way).
Any help, suggestions, ideas or comments will be greatly appreciated - thank you!
IOC Container
this.unityContainer = new UnityContainer()
.RegisterType<IDataProvider, DataProvider>()
.RegisterType(typeof(IEmailer), typeof(Emailer))
.RegisterType<DbContext, MyDataContext>(new HierarchicalLifetimeManager());
Import class (main thread)
public class DataSyncer : IDataSyncer
{
public DataSyncer(IDataProvider dataProvider, IEmailer emailer) {
this.dataProvider = dataProvider;
this.emailer = emailer;
}
public void Import(Guid key) {
// some import code
emailer.EmailAddress = "someone#somewhere.com";
emailer.Subject = "subject line";
new Thread(emailer.SendMail).Start(); // send email in new thread
}
}
Emailer class (for child threads)
public class Emailer : IEmailer
{
[Dependency]
public IDataProvider DataProvider { get; set; }
// etc
}
DataProvider (contains datacontext via ctor injection)
public DataProvider(MyDataContext context, // etc) { // etc }
I'm trying to rephrase your explanation to see if I got it right.
Your importer runs on the main thread. You fire of emails for every row you import. Your emailer needs to write audit information to the database upon success or failure of the process.
The emailer is injected into your importer and both have a dependency on a class derived from DbContext? Is that the same instance of the DbContext? If so: Why do you share that instance? Isn't each task of sending an email independent from all other tasks? If so, remove the HierarchicalLifetimeManager.
You use property injection for your IDataProvider. I understood that this is a must-have dependency. If that is the case you should use constructor injection like you already do for the other classes. By the way: Don't use the DependencyAttribute. You can also configure property injection using InjectionProperty in your call to RegisterType.
Update
As far as I know Unity never cleans up after itself. Meaning I would not expect it to call Dispose on your DbContext anyway. Do you have a reference where it says that the HierarchicalLifetimeManager disposes objects properly? I would be very interested to read it!
HierarchicalLifetimeManager works the same way as ContainerControlledLifetimeManager as long as you don't deal with child containers. That basically means that you have a single instance of your context across all threads. If you just remove that lifetime manager you would get a new instance whenever one is needed as a dependency. That should solve your problem.
If you need to take care of the disposal of your context instances I would inject a factory for the context instead of an instance. Just declare a ctor parameter of Type Func<MyDataContext> Unity will automatically generate the delegate for you (that feature is called automatic factories btw.). Then you can use using(var ctx = dbContextFactory()) { ... }.

Issues with Entity Framework Self Tracking Entities and ASP MVC .NET and Managed Extensibility Framework

BIG EDIT: This problem is probably being caused by MEF!
I'm using a service oriented architecture and have all my MVC controllers perform actions through the services.
I have a base service that looks like this:
public abstract class BaseService
{
protected MyObjectModel context;
public BaseService()
{
context = new MyObjectModel();
}
}
I then have services that inherit
[Export(typeof(IEmployeeService))]
public class EmployeeService : BaseService, IEmployeeService
{
public void NewEmployee(Employee newEmployee)
{
context.Employees.AddObject(newEmployee);
context.SaveChanges();
}
}
I have my controllers also inheriting from a base class that provides access to all the required services so they can just call:
EmployeeService.AddEmployee(new Employee() { Name = "JohnDoe"});
This all worked wonderfully until I started seeing that the ObjectContext wasn't accurately reflecting the database upon construction.
I put a breakpoint in the BaseService constructor and using Sql Server's Profiler saw that the brand new MyObjectModel wasn't even hitting the DB but pulling the data out of some cache presumably?
I stumbled upon the MergeOption property of the collections in the context and changing that made sure the data was fresh, but now I need to use that everytime I create a new service method that returns entities!
EDIT:
I've been stumbling along until I realised that my issues were probably being caused by MEF.
I have overridden the default ControllerFactory and implemented one that uses MEF to instantiate the services. What I'm probably seeing is MEF keeping the objects alive between calls.
So
1) Where can I read more on this behaviour? And what can I do to stop it and force a fresh composition every time the object is called?
Thanks.
I solved this issue eventually after hours of pulling out my hair.
My implementation of ControllerFactory looked like this.
public class ControllerFactory : IControllerFactory
{
CompositionContainer container;
DefaultControllerFactory controllerFactory;
public ControllerFactory()
{
container = new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
controllerFactory = new DefaultControllerFactory();
}
public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
{
var controller = controllerFactory.CreateController(requestContext, ControllerName);
container.ComposeParts(controller);
return controller;
}
public void ReleaseController(IController controller)
{
var disposable = controller as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
}
And I called this line in my Application Startup.
ControllerBuilder.Current.SetControllerFactory(new ControllerFactory());
What was happening was that the controller factory was only being initialised once per AppDomain cycle and therefore my composition container was as well. My service classes weren't marked specifically for Shared or Non Shared usage, so the container held onto a reference of each one. Every time the ControllerFactory created a new controller on each call it would populate the service properties with the references it still held from the last call, including the old ObjectContext which was resulting in the mismatch in data.
My entire problem was solved by adding
[PartCreationPolicy(CreationPolicy.NonShared)]
to each service enforcing a fresh version each time.
Now I'm left to wonder if MEF is STILL holding onto thos references, because that ObjectContext is not a small thing to hold onto. Is this a memory leak waiting to happen?

Categories

Resources