Entity Framework not refreshing data when using Repository Pattern - c#

I am using the repository and unit of work patterns and dependency injection to access the database with entity framework 5 in my web application. I have a User class from which Entity Framework generates a Code-First database.
public class User
{
public Guid UserId { get; set; }
public string UserName { get; set; }
.
.
.
public string LanguagePreference { get; set; }
public virtual List<Role> Roles { get; set; }
public virtual List<Branch> Branches { get; set; }
}
I have a UserService class that is used to Add or Update users. This class takes an IUserUnitOfWork as a parameter in the constructor and Unity injects a UserUnitOfwork. The IUserUserOfWork contains an IRepository<User>, an IRepository<Location> and an IRepository<Role>. These are set as Repository<T> by the DI bootstrapper. The IUserUnitOfWork sets up the different Repositories with the same entity framework DbContext. I did this as I was having issues updating the many-to-many relationships related to the User (Locations and Roles).
UserUnitOfWork:
public IRepository<Branch> BranchRepository {get; set;}
public IRepository<Role> RoleRepository { get; set; }
public IRepository<User> UserRepository { get; set; }
public DbContext Context { get; set; }
public UserUnitOfWork(DbContext context, ITransientErrorDetectionStrategy errorDetectionStrategy,RetryStrategy retryStrategy )
{
Context = context;
BranchRepository = new Repository<Branch>(context, errorDetectionStrategy, retryStrategy);
RoleRepository = new Repository<Role>(context, errorDetectionStrategy, retryStrategy);
UserRepository = new Repository<User>(context, errorDetectionStrategy, retryStrategy);
}
The Repository class then uses Entity Framework 5 to access the database.
Example of method from Repository.FirstOrDefault:
public virtual T FirstOrDefault(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, string includeProperties = "")
{
T result = null;
_retryPolicy.ExecuteAction(() =>
{
IQueryable<T> entities = GetHelper(filter, orderBy, includeProperties);
result = entities.FirstOrDefault();
});
return result;
}
And Update from Repository:
public virtual void Update(T entity)
{
if (_dbContext.Entry(entity).State == System.Data.EntityState.Detached)
{
_dbContext.Set<T>().Attach(entity);
_dbContext.Entry(entity).State = System.Data.EntityState.Modified;
}
}
So my problem now is that when I update the User it correctly updates the data in the database, and when I log out and log in the initial change works. However if I update again and log out and in the new change isn't picked up even though the database is updated.
I'm beginning to fear that the approach I've taken is incorrect, can someone tell me how to make sure that when I do an update Entity Framework will always get the latest version?
EDIT:
So I've created a Per Request Lifetime Manager like so:
public class PerHttpRequestLifetimeManager : LifetimeManager
{
private readonly object key = new object();
public override object GetValue()
{
if (HttpContext.Current != null &&
HttpContext.Current.Items.Contains(key))
return HttpContext.Current.Items[key];
else
return null;
}
public override void RemoveValue()
{
if (HttpContext.Current != null)
HttpContext.Current.Items.Remove(key);
}
public override void SetValue(object newValue)
{
if (HttpContext.Current != null)
HttpContext.Current.Items[key] = newValue;
}
}
In my DI bootstrapper I now setup my domain context like below:
container.RegisterType<DbContext, DomainContext>(new PerHttpRequestLifetimeManager());
It still doesn't appear to be working, am I missing something else or am I setting it up incorrectly?
EDIT 2:
Just to point out the architecture:
We have an MVC application which uses Angular JS to make ajax calls to a Web Api service layer. The Web Api has an ISomethingService injected into it. It is this ISomethingService that has the repositories injected into it. Would there be some confusion for the PerHttpRequestLifetimeManager since there is both an MVC and Web API project running?
EDIT 3:
An example of how I am saving the edited user:
We have a UserModel class that is used for communications between the ServiceLayer -> API -> UI layer and back. The User class is the one generated by Entity Framework code first. The EditUser method in the UserService takes in a UserModel.
I then user the _unitOfWork.UserRepository to get the corresponding database user
var editedUser = _unitOfWork.UserRepository.FirstOrDefault(x => x.UserId == userModel.UserId);
I map the fields from the userModel to the editedUser and I then call (in the UserService)
_unitOfWork.UserRepository.Update(editedUser)
and after
_unitOfWork.Save()
YET ANOTHER EDIT:
So I have edited a simple method that updates a single text field on the user table (Language Preference). I explicitly call the dispose method after the update to ensure I am disposing the method.
public void SetUserLanguagePreference(Guid userId, string language)
{
var user = _unitOfWork.UserRepository.FirstOrDefault(x => x.UserId == userId);
user.LanguagePreference = language;
_unitOfWork.UserRepository.Update(user);
_unitOfWork.Save();
_unitOfWork.Dispose();
}
UnitOfWork.Dispose() calls the dispose method of the repositories and the Dbcontext
The database updates correctly. However the behaviour is still incorrect. When I log out and in first it retrieves the correct value. When I change it again and log out and in again it doesn't update. This has been the pattern before, it get the first update after I log out and in, but if I change again and log out and in it doesn't pick it up.

Finally, not an edit but an answer! We use Claims based authentication and have a class that overrides the ClaimsPrinciple Authenticate method that is called whenever a user is authenticated.
public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
{
if (incomingPrincipal.Identity.IsAuthenticated)
{
//Check here if the authenticated user has access to this system
//using the user repository and if so add more claims to the token
}
return base.Authenticate(resourceName, incomingPrincipal);
}
It was not possible to inject into this method using DI as it always went to the empty constructor (not sure why but that's the way it is).
So instead we were setting the repository in the empty constructor like so:
public PRAuthenticationManager()
{
_userRepository = DiBootstrapper.Container.Resolve<IRepository<User>>();
}
When the Authenticate method is called we check our database for a user with the claims attached to the ClaimsPrincipal. If we make a match we add new claims to the token which are then used for each call to the Web Api later. This repository was not being disposed (even if all the others were) and so when a user logged out and in they got data from that same context which had not been disposed from the last time the user logged in.
Three full days trying to find that one....

See if this helps: How do I get Entity Framework 5 to update stale data
I ran into the same problem, it doesn't refresh from the database if you already have the object in your ObjectContext, of course, this would only work on a per object basis, but that might be just what you need.

Related

How can I get sorting, paging and filtering on a Repository without MVC

I'm trying to create just the back-end part for a simple CRUD project. I'm completely new to asp.net and currently reading as I go. But I got stuck.
I've created the entities (models) I need
public class VehicleMakeEntity
{
public int Id { get; set; }
public string Name { get; set; }
public string Abrv { get; set; }
public VehicleMakeEntity Make { get; set; }
}
I've also created a standard DbContext class and the repositories
class MakeRepository : IMakeRepository
{
ProjectDbContext context;
public MakeRepository(ProjectDbContext context)
{
this.context = context;
}
public void Delete(VehicleMakeEntity entity)
{
context.VehicleMake.Remove(entity);
context.SaveChanges();
Console.WriteLine(entity.Make.Name);
}
public void Insert(VehicleMakeEntity entity)
{
context.VehicleMake.Add(entity);
context.SaveChanges();
}
public void Update(VehicleMakeEntity entity)
{
context.VehicleMake.Update(entity);
context.SaveChanges();
}
public void Dispose()
{
context.Dispose();
}
}
Now the problem I have is I cannot find any documentation that both doesn't use MVC and uses repositories.
I need to create a service class that implements basic paging, sorting and filtering but everything I look at Like this uses MVC and I have no idea how to convert it to my project.
Based on your code and comments, you have a setup that is meant for .NET Core web apps that can be implemented with services (dependency injection). You can, however, run the entire dependency injection setup on a console based app that doesn't host a web app.
First, you will need to add the Microsoft.AspNetCore.All package so you get all the classes you might be using (mainly Microsoft.Extensions.DependencyInjection).
You can now build your service provider something like this:
var provider = new ServiceCollection()
.AddDbContext<ProjectDbContext>(config => // connection here)
.AddScoped<IMakeRepository, MakeRepository>()
.BuildServiceProvider();
You can now fetch any service you want out of your provider. The above code also allows you to add any service you find in any .NET Core MVC tutorial since it uses the same classes and libraries. Let's say you want to fetch the IMakeRepository, you can use the following:
var makeRepo = provider.GetService<IMakeRepository>();
You can now test out the functions inside your makeRepo object.

Save Identity profile in separate database

I am planning to implement MVC 5.0 ASP.Net identity in a brand new application. I referred to the Microsoft article http://go.microsoft.com/fwlink/?LinkID=317594 to add the customer profile information in a separate table other than the identity tables.
However according my requirement, I would like to store the customer profile information in a separate database in order to segregate the user identity information and customer profile information in database level. The Identity uses single data store while creating user and the profile information, whereas I need to set two different store for the user and profile information. Do Anyone have any suggestions on this?
You could simply write a custom UserStore class and extend default UserStore class. Consider this simple example:
public class ApplicationUser : IdentityUser
{
// other codes
// Add your extra profile information
// By Adding NotMapped attribute EF omits this and dose not puts in Identity's table
[NotMapped]
public Profile Profile { get; set; }
}
public class Profile
{
public int ID { get; set; }
public string ExtraData { get; set; }
// other properties
}
Now we need custom User Store to put and fetch data from 2 DB
public class MyUserStore : UserStore<ApplicationUser>
{
public MyUserStore(DbContext context)
: base(context)
{
// other implementation for second DB
}
public override Task CreateAsync(ApplicationUser user)
{
// save Profile object to separate DB
_mySecondDB.Save(User.Id, user.Profile);
return base.CreateAsync(user);
}
public override Task UpdateAsync(ApplicationUser user)
{
// same pattern as CreateAsync
}
public override Task DeleteAsync(ApplicationUser user)
{
// same pattern as CreateAsync
}
public override async Task<ApplicationUser> FindByIdAsync(string userId)
{
var user = await base.FindByIdAsync(userId);
user.Profile = _mySecondDB.FindProfileByUserId(userId);
return user;
}
public override Task<ApplicationUser> FindByNameAsync(string userName)
{
// same pattern as FindByIdAsync
}
}
Now you just need to inject your custom User Store in Identity pipeline. To do so change ApplicationUserManager.Create static method in App_Start\IdentityConfig.cs like this:
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(
new MyUserStore(context.Get<ApplicationDbContext>()));
// other codes
}

Managing DbContext in WPF MVVM application

I've been banging my head with this for days and still can't decide on which is the correct approach.
This question is targeting WPF specifically since as opposed to a web-application, many posts and articles online recommends a context per view-model approach and not a context per request.
I have a WPF MVVM application which is using an Entity-Framework DB first model.
here is an example of two models used in my app (created by EF Designer):
public partial class User
{
public User()
{
this.Role = new HashSet<Role>();
}
public string ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Role> Role { get; set; }
}
public class Role
{
public Role()
{
this.User = new HashSet<User>();
}
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<User> User { get; set; }
}
I've narrowed my options on how to handle this to the following:
1) Creating a DataAccess class which creates and disposes of the DbContext on each method call:
public class Dal
{
public User GetUserById(object userId)
{
using (var db = new DbEntities())
{
return db.User.Find(userId);
db.SaveChanges();
}
}
public void RemoveUser(User userToRemove)
{
using (var db = new DbEntities())
{
db.User.Remove(userToRemove);
db.SaveChanges();
}
}
}
which I can use in my ViewModel as follows:
public class UserManagerViewModel : ObservableObject
{
private readonly Dal dal = new Dal();
// models...
//commands...
}
2) Similar to approach 1 but without the Using statements:
public class Dal : IDisposable
{
private readonly DbEntities db = new DbEntities();
public User GetUserById(object userId)
{
return db.User.Find(userId);
db.SaveChanges();
}
public void RemoveUser(User userToRemove)
{
db.User.Remove(userToRemove);
db.SaveChanges();
}
public void Dispose()
{
db.SaveChanges();
}
}
The use is the same inside the ViewModel
3) Create a repository for each entity. Looks the same as the above options (also has the with or without the using dilemma), however every repository contains only methods related to its entity.
Afaik the use is the same as above inside my ViewModel.
4) Create a Unit-Of-Work class that will pass the appropriateRepository on demand:
public class UnitOfWork : IDisposable
{
private DbEntities db = new DbEntities();
private IUserRepository userRepository;
public IUserRepository UserRepository
{
get
{
return userRepository ?? new UsersRepository(db);
}
}
public void Save()
{
db.SaveChanges();
}
public void Dispose()
{
db.Dispose();
}
}
and use it inside my ViewModel as follows:
public class UserManagerViewModel : ObservableObject
{
private readonly UnitOfWork unit = new UnitOfWork();
// models...
//commands...
}
Which of the above approach (if any) is preferred in terms of in terms of data concurrency, better abstraction and layering and overall performance?
EDIT - Found the following paragraph in this article. :
When working with Windows Presentation Foundation (WPF) or Windows Forms, use a context instance per form. This lets you use change-tracking functionality that context provides.
However, it raises the question of whether I should create a DbContext object in my view-model or is it better to have a utility class such as my DAL class and reference it.
This is what dependency injection frameworks are designed to solve. Yes, it's yet another technology to add to your project, but once you start using DI you never look back.
The real problem here is that you're trying to make this decision in your view models when you really should be employing inversion of control and making the decision higher up. A WPF/MVVM application will want a context per-form so that changes are only submitted once a user is finished editing, and also to give the user the opportunity to cancel the changes. I know you're not using this in a web application but a well-designed architecture means you should be able to, in which case you'll want a context per request. You may want to write a console-app utility that populates the database with static data, in this case you may want a global/singleton context for performance and ease-of-use. Lastly, your unit tests also need to mock the context, probably on a per-test basis. All four of these cases should be set up in your injection framework and your view models should neither know or care about any of them.
Here's an example. I personally use Ninject, which is specifically designed for .NET. I also prefer NHibernate, although the choice of ORM is irrelevant here. I have session objects that have different scoping requirements, and this gets set up in a Ninject module that initializes my ORM classes:
var sessionBinding = Bind<ISession>().ToMethod(ctx =>
{
var session = ctx.Kernel.Get<INHibernateSessionFactoryBuilder>()
.GetSessionFactory()
.OpenSession();
return session;
});
if (this.SingleSession)
sessionBinding.InSingletonScope();
else if (this.WebSession)
sessionBinding.InRequestScope();
else
sessionBinding.InScope(ScreenScope);
This sets up the scoping for an ISession, which is the NHibernate equivalent of your context class. My repository classes, which manage the database objects in memory, contain a reference to the session they are associated with:
public class RepositoryManager : IRepositoryManager
{
[Inject]
public ISession Session { get; set; }
... etc...
{
The [Inject] attribute tells Ninject to populate this field automatically using the scoping rules I've set up. So far this is all happening in my domain classes, but it extends to my view model layer as well. In my scoping rules I pass in an object called "ScreenScope", and while I won't go into it here it basically means that any time I ask for a session object in my ScreenViewModel, or any view models that it has as members (including their own children) the same ISession object gets automatically created and passed in to all of them. By using DI scoping I don't even have to think about it, I just declare the members with the [Inject] attribute and it happens:
public class ScreenViewModel
{
[Inject] public CustomerService CustomerService { get; set; }
[Inject] public SalesService SalesService { get; set; }
[Inject] public BillService BillService { get; set; }
...etc...
}
These service classes all contains a RepositoryManager that has been injected, and since they're all in ScreenViewModel the ISession object will be the same, at least in my WPF build. if I switch to my MVC build they're the same for all view models created for a given request, and if I switch to a console build it uses the same ISession for everything in the entire program.
TL;DR: Use dependency injection and a scope your contexts to one-per-form.
In my earlier usage of MVVM within WPF I was utilising an open context per VM but I quickly ran into issues with thread safety of DBContexts once applications evolved to make better use of Async.
Whilst there is a greater development overhead, I now utilise dependency injection to provide a DBContextFactory (not the DBContext itself). I spin up a context in a using statement witihn the VM to fill observableCollections with plinq calls via EF. Another performance benefit of this method is running queries with AsNoTracking(). The annoying part is managing the reattachment of new or modified objects to the short lived context:
shortDBContext.Attach(myEntity).State = EntityState.Added; // or modified
await shortDBContext.SaveChangesAsync();

MVC 5 IoC and Authentication

I am just about to start on a project, where I will be using MVC5. But as I want to use IoC and later reuse my user tables, and add custom stuff to it, I am finding it very hard to see how I can use the new Identity framework that came with MVC5.
I am more and more looking towards basic forms auth. What are your solutions?
My needs:
User repository/service must be injected
User repository must reside in the DAL
User repository must be able to support other technologies than EF
Authentication with OpenID and OAuth must be somewhat easy to implement
MUST BE SECURE
Should be reusable in other projects, eg. WPF
I have been looking for a long time for an answer, but everything I see is hardcoded in the controller.
How are you solving this? Are you writing most from scratch, or can you bind into something that will scale to other .NET platforms as WCF and WPF?
The below code is taken directly from the AccountController in the default ASP.NET MVC 5 Template.
The first thing it does is a Bastard Injection.
[Authorize]
public class AccountController : Controller
{
public AccountController()
: this(
new UserManager<ApplicationUser>(
new UserStore<ApplicationUser>(
new ApplicationDbContext())))
{
}
public AccountController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
}
The accepted answer will go to the person, that shows me what they have done, that incorporates the above requirements
Since this is .NET, the standard approach to security is to authenticate at the application boundary, and convert the authentication information into an IPrincipal. MVC supports this out of the box.
If you need other information gained during authentication, you can gather that at in the Composition Root and use it to compose your services.
As an example, imagine that you need the authenticated user's email address in a lower layer. Any class that requires the user's email address can simply request it as a Concrete Dependency:
public class EmailThingy
{
private readonly string userEmail;
public EmailThingy(string userEmail)
{
if (userEmail == null)
throw new ArgumentNullException("userEmail");
this.userEmail = userEmail;
}
// other members go here...
}
In ASP.NET MVC, the Composition Root is IControllerFactory. IIRC, you can pull the authentication data from within the CreateController method and use it to compose your object graph.
These days, I use IPrincipal in the same way: I inject it as a dependency, instead of relying on the Thread.CurrentPrincipal Ambient Context, because it's easier to unit test when everything is consistently injected via Constructor Injection.
You might be interested to get a look at Thinktecture.IdentityServer.v2 https://github.com/thinktecture/Thinktecture.IdentityServer.v2. Many of your concerns are already implemented and encapsulated. If you don't find what you need you'll have to think about how to abstract all these concerns and implement it on your own.
I ended up deciding to implement the IUserStore, IUserStore, IUserPasswordStore, IUserLoginStore, to be able to move the UserRepository down into it's rightful place, the DataAccess Layer. But still get the Security Benifits of the Owin and new Identity Framework.
It's quite easy to implement, and doesn't take much to abstract it. Here is a taste of the UserStoreWrapper
namespace qubis.booking.WebApp.App_Code.Identity
{
public class UserServiceWrapper : IUserStore<ApplicationUserWrapper>,
IUserPasswordStore<ApplicationUserWrapper>,
IUserLoginStore<ApplicationUserWrapper>
{
public IUserRepository UserRepos { get; set; } // My own Interface.
public UserServiceWrapper(IUserRepository userRepo)
{
UserRepos = userRepo;
}
public async Task CreateAsync(ApplicationUserWrapper user)
{
UserRepos.Insert(user.RealUser);
}
public async Task<ApplicationUserWrapper> FindByIdAsync(string userId)
{
var appUser = UserRepos.FindByUserName(userId);
ApplicationUserWrapper wrappedUser;
if (appUser != null)
{
wrappedUser = new ApplicationUserWrapper(appUser);
}
else
wrappedUser = null;
return wrappedUser;
}
In the Account controller I Simply just ask for it to be injected:
public AccountController(UserManager<ApplicationUserWrapper> userManager)
{
UserManager = userManager;{ AllowOnlyAlphanumericUserNames = false };
}
And as I am using Ninject I just set it upin the kernel like so:
// <summary>
// Load your modules or register your services here!
// </summary>
// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IUserStore<ApplicationUserWrapper>>().To<UserServiceWrapper>();
kernel.Bind<UserManager<ApplicationUserWrapper>>().ToSelf();
}
To see the Identity frameworks structure, please see this article. http://www.asp.net/identity/overview/extensibility/implementing-a-custom-mysql-aspnet-identity-storage-provider
If all you need is to inject custom UserStore implementation this article may help you
Basically you need to inject this (depends if you want to use roles, claims etc..):
Write a User class that implements the IUser interface
public class IdentityUser : IUser {
public IdentityUser(){...}
public IdentityUser(string userName) (){...}
public string Id { get; set; }
public string UserName { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
}
Write a User store class that implements the IUserStore, IUserClaimStore, IUserLoginStore, IUserRoleStore and IUserPasswordStore
public class UserStore : IUserStore<IdentityUser>,
IUserClaimStore<IdentityUser>,
IUserLoginStore<IdentityUser>,
IUserRoleStore<IdentityUser>,
IUserPasswordStore<IdentityUser> {
public UserStore(){...}
public Task CreateAsync(IdentityUser user){...}
public Task<IdentityUser> FindByIdAsync(string userId){...}
.. .
}

Multiple Ajax Requests per MVC 4 View

I'm using the repository pattern with a context and ninject as the IOC. I have a service which handles getting and setting page properties in the database.
public class MyContext : DbContext
{
public MyContext() : base ("DefaultConnection")
{
}
public DbSet<PageProperty> PageProperties { get; set; }
public DbSet<Contact> Contacts { get; set; }
}
public class DefaultRepository : IRepository
{
MyContext _context;
public DefaultRepository(MyContext context)
{
_context = context;
}
public IQueryable<PageProperty> PageProperties { get { return _context.PageProperties; } }
public IQueryable<Contact> Contacts { get { return _context.Contacts; } }
}
public class ModuleLoader : NinjectModule
{
public ModuleLoader()
{
}
public override void Load()
{
var context = new MyContext();
context.Database.Initialize(false);
Bind<MyContext>().ToConstant(context).InSingletonScope();
Bind<IRepository>().To<DefaultRepository>();
Bind<IPagePropertyProvider>().To<DefaultPagePropertyProvider>().InSingletonScope();
}
}
public class DefaultPagePropertyProvider : IPagePropertyProvider
{
IRepository _repository;
object _syncLock = new object();
public DefaultPagePropertyProvider (IRepository repository)
{
_repository = repository;
}
public string GetValue(string pageName, string propertyName
{
lock (_syncLock)
{
var prop = page.PageProperties.FirstOrDefault(x => x.Property.Equals(propertyName) && x.PageName.Equals(pageName)).Value;
return prop;
}
}
public void SetValue(string pageName, string propertyName, string value)
{
var pageProp = _repository.PageProperties.FirstOrDefault(x => x.Property.Equals(propertyName) && x.PageName.Equals(pageName));
pageProp.Value = value;
_repository.SaveSingleEntity(pageProp);
}
}
In my view I am doing 3 ajax calls, one to get a list from contacts to fill out a table, one ajax call to determine how many pages i have depending on the page size I'm using, and one ajax call to set the page size that I want to use. so a select box changes the page size (How many contacts per page: [ 30]) , a table that displays the contacts (generated from jquery which decifers json), and finally a div containing a list of page numbers to click. The workflow is, call GetContacts(), this function then queries the PageProperties to find out the page size to use, then call GetPages(), this function also queries PageProperties to find out what page size to use, SetPageSize() which sets the page size. So GetContacts() and GetPages() is used when a page is selected from the div, SetPageSize() then GetContacts() and GetPages() is called when the select box change event is fired. GetContacts() and GetPages() is only called when the first SetPageSize() $.ajax request is done() and there is a success from that function.
Now, before I added lock(syncLock) in the DefaultPageProperty service and before I added InSingletonScope to both that service and the context, I was getting two errors.
The connection was not closed. The connection's current state is connecting.
An EdmType cannot be mapped to CLR classes multiple times
I assumed because the connection was in a connecting state, that the context was being reused and reused and reused, so I thought putting that to SingletonScope() would mean that only one connection was made, then I thought the same about DefaultPageProperty and then because I was making async calls to that service, I should put a lock over the database querying.
It works, and the problems don't exist. But I don't know if what I have done is correct within the pattern I'm using, I'm wondering if I've missed something fundamental? My question is, is this a proper/viable solution which won't create any caveats later down the road? Have I actually solved the issue or just created more?
I redesigned the way I do my context now.
I have my context then I implement IDbContextFactory<TContext> called DefaultContextFactory<MyContext> and I inject them.
In the Repository I have in the public constructor _context = contextFactory.Create();.
Then throughout the repository i just use _context.WhatEver() and its fine.
I also did in the ModuleLoader Bind<IRepository>().To<DefaultRepository>().InTransientScope() in order to make every call to it create a new repository!
I don't need a repository factory because I only have one repository!

Categories

Resources