Async methods on ICollection with EF6 - asynchronous

My domain objects define collections as virtual ICollection<type>. I want to use async methods in my repositories and services but it is not available.
How do I use async methods on my EF properties?

Related

Multi-Tenant ASP.NET Core

How would you configure the middleware to change the DBContext connection string based on a sub-domain of the income request?
It appears that the DBContext is set in the Startup... which looks too early to determine the HTTPRequest to resolve the connection string.
Well, this might not suit your needs entirely, but here's what I would do:
Create a DbContextFactory class. This DbContextFactory class can create instances of the DbContext and can pass in any string to the DbContext constructor. Then inject this factory and whenever you need an instance of the dbcontext, just ask the factory to return one for you. Of course you have to manage the lifetime of the created contexts yourself (i.e. using block).
Another option can be to create the DbContextFactory so that it holds an instance of a DbContext. When you ask for a context object from the factory, the factory creates a new one and also stores it in a private field, and subsequent calls return that same instance. Make the factory IDisposable and in its Dispose() method, dispose the context as well. This way you don't have to worry about managing lifetime (if you use a Scoped registration).

How to use async await in asp.net membership provider ValidateUser method?

I'm using an asp.net 4.5 web application and asp.net membership. I implement the MembershipProvider interface which has a method:
public override bool ValidateUser(string username, string password)
The code within this method for my implementation has to make two WCF service calls which can be expensive. In the spirit and my desire of learning and using async, I'd like to make the code use async await.
I created my two Tasks that need to call the WCF service methods. What I'm unclear on is how to properly use async from the "ValidateUser" method to call these Tasks. I cannot change this method signature to add async as I would have to then change bool to Task so I'm stuck with a method signature that cannot be adored with the async modifier.
In this case how can I call my two tasks and have them run on a background thread? I know I can use Task.Result but my understanding is that would be a synchronous call and is frowned upon. I'm not sure of the gain by using Task.Result as my intention is to background thread my two WCF service method calls.
Well, you can certainly call the tasks asynchronously inside your membership provider, you just can't call ValidateUser asynchronously.
The old Membership API was created long before Async existed and is not compatible. You could wrap this around an async method. Here's a blog entry about it.
http://blogs.msdn.com/b/pfxteam/archive/2012/03/24/10287244.aspx
The gist is something like this (change to use for ValidateUser)
public Task SleepAsync(int millisecondsTimeout)
{
return Task.Run(() => Sleep(millisecondsTimeout));
}

EF6 (code first), MVC, Unity, and a service layer without a repository

My application is using SQL Server 2012, EF6, MVC and Web API.
It's also using a repository and assorted files such as:
DatabaseFactory.cs
Disposable.cs
IDatabaseFactory.cs
IRepository.cs
IUnitOfWork.cs
RepositoryBase.cs
UnitOfWork.cs
We already use a service layer between our controllers and the repository
for some complicated business logic. We have no plans EVER to change to a different database and it has been pointed
out to me that the recent thinking is that EF6 is a repository so why build
another repository on top of it and why have all of the files I have above.
I am starting to think this is a sensible approach.
Does anyone know of any examples out there that implement EF6 without a
repository, with a service layer. My search on the web has revealed many
complex code examples that seem over complicated for no reason at all.
My problem is also when using a Service Layer then where do I put:
context = new EFDbContext()
In the controller, the service layer or both ? I read that I can do this with dependancy injection. I already use Unity as an IOC but I don't know how I can do this.
Entity Framework IS already a Unit of Work pattern implementation as well as a generic repository implementation (DbContext is the UoW and DbSet is the Generic Repository). And I agree that it's way overkill in most apps to engineer another UoW or Generic Repository on top of them (besides, GenericRepsitory is considered to be an anti-pattern by some).
A Service layer can act as a concrete repository, which has a lot of benefits of encapsulating data logic that is specific to your business needs. If using this, then there is little need to build a repository on top of it (unless you want to be able to change your backend service technology, say from WCF to WebApi or whatever..)
I would put all your data access in your service layer. Don't do data access in your controller. That's leaking your data layer into your UI layer, and that's just poor design. It violates many of the core SOLID concepts.
But you do NOT need an additional UnitOfWork, or other layers beyond that in most cases, unless your apps are very complex and intended to work in multiple environments...
Setting up Unity for ASP.NET MVC and WebAPI is quite easy if you install and add the Unity.Mvc* and Unity.WebAPI* Nuget packages to your project. (The * is a version number, like 3 or 4 or 5. Look for the appropriate versions for your project. Here are for example the links to the Unity.Mvc 5 package and to the Untity.WebAPI 5 package.)
The usage of these packages is explained in this blog post.
The building blocks are roughly like so:
You build a unity container and register all your dependencies there, especially the EF context:
private static IUnityContainer BuildContainer()
{
var container = new UnityContainer();
container.RegisterType<MyContext>(new HierarchicalLifetimeManager());
container.RegisterType<IOrderService, OrderService>();
container.RegisterType<ICustomerService, CustomerService>();
container.RegisterType<IEmailMessenger, EmailMessenger>();
// etc., etc.
return container;
}
MyContext is your derived DbContext class. Registering the context with the HierarchicalLifetimeManager is very important because it will ensure that a new context per web request will be instantiated and disposed by the container at the end of each request.
If you don't have interfaces for your services but just concrete classes you can remove the lines above that register the interfaces. If a service needs to be injected into a controller Unity will just create an instance of your concrete service class.
Once you have built the container you can register it as dependency resolver for MVC and WebAPI in Application_Start in global.asax:
protected void Application_Start()
{
var container = ...BuildContainer();
// MVC
DependencyResolver.SetResolver(
new Unity.MvcX.UnityDependencyResolver(container));
// WebAPI
GlobalConfiguration.Configuration.DependencyResolver =
new Unity.WebApiX.UnityDependencyResolver(container);
}
Once the DependencyResolvers are set the framework is able to instantiate controllers that take parameters in their constructor if the parameters can be resolved with the registered types. For example, you can create a CustomerController now that gets a CustomerService and an EmailMessenger injected:
public class CustomerController : Controller
{
private readonly ICustomerService _customerService;
private readonly IEmailMessenger _emailMessenger;
public CustomerController(
ICustomerService customerService,
IEmailMessenger emailMessenger)
{
_customerService = customerService;
_emailMessenger = emailMessenger;
}
// now you can interact with _customerService and _emailMessenger
// in your controller actions
}
The same applies to derived ApiControllers for WebAPI.
The services can take a dependency on the context instance to interact with Entity Framework, like so:
public class CustomerService // : ICustomerService
{
private readonly MyContext _myContext;
public CustomerService(MyContext myContext)
{
_myContext = myContext;
}
// now you can interact with _myContext in your service methods
}
When the MVC/WebAPI framework instantiates a controller it will inject the registered service instances and resolve their own dependencies as well, i.e. inject the registered context into the service constructor. All services you will inject into the controllers will receive the same context instance during a single request.
With this setup you usually don't need a context = new MyContext() nor a context.Dispose() as the IOC container will manage the context lifetime.
If you aren't using a repository then I assume you would have some place to write your logic/processing that your service operation would use. I would create a new instance of the Context in that logic/process class method and use its methods directly. Finally, dispose it off right after its use probably under a "using".
The processing method would eventually transform the returned/processed data into a data/message contract which the service returns to the controller.
Keep the data logic completely separate from Controller. Also keep the view model separate from data contract.
If you move ahead with this architecture, you are going to be tightly coupling the Entity Framework with either your service or your controller. The repository abstraction gives you a couple things:
1) You are able to easily swap out data access technologies in the future
2) You are able to mock out your data store, allowing you to easily unit test your data access code
You are wondering where to put your EF context. One of the benefits of using the Entity Framework is that all operations on it are enrolled into a transaction. You need to ensure that any data access code uses the same context to enjoy this benefit.
The design pattern that solves that problem is the Unit of Work pattern, which by the looks of things, you are already using. I strongly recommend continuing to use it. Otherwise, you will need to initialize your context in your controller, pass it to your service, which will need to pass it to any other service it interacts with.
Looking at the objects you have listed, it appears to be a considerate attempt to build this app with enterprise architectural best practices. While abstractions do introduce complexity, there is no doubting the benefit they provide.

Injecting a service into an implementation of NHibernate's IUserType using Autofac

I'm using NHibernate to map the following class to an Oracle database in my ASP.NET MVC application:
public class User
{
// Needs to be encrypted/decrypted when persisting
public virtual string Question { get; set; }
}
Following several examples that I've found, I would like to use an implementation of NHibernate's IUserType to transform my data when it is persisted to or retrieved from my database example.
Since I have already written an EncryptionService class to handle data encryption in other parts of my application, I would like to inject it into my user type. Is there a way to perform constructor injection on an IUserType using Autofac?
NHibernate is responsible for creating instances of IUserType implementations. If you want this configurable, you could query the service from the AutoFac container (obviously this isn't dependency injection, more of service locator). Or you could implement IConfigurable, which allows you to take in a Dictionary of parameters. One of those parameters could be a class name.
Use the Autofac's BytecodeProvider which you can find in Autofac contrib.
http://chadly.net/post/2009/05/28/Dependency-Injection-with-NHibernate-and-Autofac.aspx
http://code.google.com/p/autofac/downloads/list

Understanding Async Methods in Web Service

I consume Java Service in my .NET appliaction. I have one question: When service serialize in .NET he also create Async methods. For example for GetPersons() method service create GetPersonsAsync() which is return void. In which cases I can use this Async methods and what the destination of these methods.
Generally, for async methods, you also need to specify a callback method. The called web method immediately returns but keeps working in the backround. When its done, it invokes your callback method with its results

Resources