Is there a way to have ASP.NET 5 Dependency Injection resolve a DbContext without a reference? - entity-framework

I am doing some prototyping with MVC 6 and have run into a quandary. Our project architecture is straightforward enough:
Data Tier (Entity Framework 6)
Service Tier (Class Library, references Data Tier)
Presentation Tier (MVC 4, references Service Tier, does not reference Data Tier)
I'm attempting to keep the design as similar to the original as possible, even after reading (and agreeing with) the Composition Root pattern. This means that my new MVC 6 application is unaware of my DbContext type. You can guess what happens when I attempt to inject one of my service classes into a controller:
Unable to resolve service for type My.Data.Tier.DbContext while attempting to activate My.Service.Tier.SomeService.
I believe that our previous implementation (I didn't write it) resolves the DbContext by reflecting assemblies in the bin folder. Is there a way I can do this (or something like it) with the new Microsoft.Extensions.DependencyInjection namespace that's built-in to ASP.NET 5/MVC 6 so I can avoid a hard reference to my data tier from my presentation tier?
Update
After reading Joe Audette's answer, I came up with a very simple extension method that I added to my service tier:
public static class ServiceCollectionExtensions
{
public static void RegisterDbContext(this IServiceCollection services)
{
services.AddScoped<My.Data.Tier.DbContext, My.Data.Tier.DbContext>();
}
}
Then, in my MVC app's Startup.cs:
using My.Service.Tier.ExtensionNamespace;
public void ConfigureServices(IServiceCollection services)
{
services.RegisterDbContext();
}

I think in the built in DI everything you need must be registered with the DI services.
To keep the data references out of your MVC app, you could have an IServiceCollection extension method in your Services tier that would register the dbcontext, or it in turn could call an extension method on the data tier.
That way your mvc app only has to have a reference on the services tier.

Related

Table confilict while integrating Identity Server 4 and Entity Framework Core together

I have generated a dotnet core project with the command “dotnet new angular …”. With individual account authentication option.
The dotnet core has generated a project with application data context like the following.
public class ApplicationDbContext : ApiAuthorizationDbContext<ApplicationUser>
{
public ApplicationDbContext(
DbContextOptions<ApplicationDbContext> options,
IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options, operationalStoreOptions)
{
}
}
I would like to integrated the identity server 4 into the same project and be served on the same instance of the api controllers. I have followed a guide linked below to store the configuration and operational store in the ef database.
http://docs.identityserver.io/en/latest/reference/ef.html
I have found out, that the DeviceCodes and Persisted Grant table are already in place in the database. while I tried to migrate the database to meet the requirements of the Operational Store.
I have looked into the ef source code, that the ApiAuthorizationDbContext class has already included the these tables to support Identity Server.
Now I am not quite sure which is the best solution
(1) Should I switch the ApplicationDbContext to extend the IdentityDbContext instead of ApiAuthorizationDbContext and use completely the way described in the guide above?
(2) Or should I skip the steps related to the OperationalStore DbContext and let the identity server 4 use the existing tables provisioned by the ApiAuthorizationDbContext? And how can I put them together?
What is the best practice? Thank you very much in advance.
In my application I took the source-code for the IdentitServer4 entitframework core NuGet packages and added them to my IdentityServer project (in a separate class library).
By doing this I get in control of how it is implemented and also how/when apply the migrations. This makes it it easier to customize it as you like.
Then having separate contexts for IdentityServer and your application needs also gives you good separation of concerns.

How to access Entity Framework DbContext entities in Server-Side Blazor Components

I'm new to .NET Core and Blazor, with mostly WebForms and MVC experience.
All the Blazor documentation and tutorials I've found use a separate API project and access data through HttpClient and Json serialization/deserialization. I see why this would be necessary for client-side Blazor using WebAssembly, but for Server-Side Blazor using SignalR what's the best way to access the database directly from the components' .razor files using an Entity Framework DbContext?
For example, in an MVC controller you can just do something like:
private ApplicationDbContext context = new ApplicationDbContext();
and then query the data by doing something like:
var things = context.Things.Where(t => t.ThingAttributes == something);
Is there an approach that is this clean and efficient when working with components in server-side Blazor?
Sorry for the broad nature of this question, feel free to point me to blogs, docs, or tutorials I should have already read. Thanks!
What you call a controller should be turned into a service class, that retrieves data from the database, and pass it to the calling methods. You should add this service to the DI container in the Startup class. To use this service in your components you should inject it like this:
#inject DataService myDataService
I think that the Blazor templates come with sample how to define such a service and use it in your components.
Here's a link to a sample by the Blazor team how to create a service and how to use it in your components. The service doesn't use Entity Framework, but this is something really minor I'm sure you'll cope with.

Is it better to use POCO objects or detached EntityFramework object to expose database via WCF?

I created a WCF service in charge of exposing my database's data since I don't want the database to be directly accessed by my application (for security reasons) and i need to be able to share data with third-party applications.
My solution is structured this way: WPF application -> WCFService library -> DataAccessLayer library. (Arrows define assembly dependencies 'depends on')
To implement the WCF service I considered to simply return detached EntityFramework objects from the service BUT it forces the main application to have a dependency on the DataAccessLayer library.
The only way i can get around that is generating POCO objects and use them to send them over the wire, but now i have to map values back and forth EntityFramework.
At the moment i'm generating POCOs dynamically via a T4 template and I'm using AutoMapper to map values back and forth EntityFramework.
The Wcf service will just have to implement the repository pattern to expose data.
Is this a good solution? Are there any other option?
Is there any shortcoming i should be aware of?
Depending on your constraints, I would have to agree with this solution.
I created an almost identical solution, although our motivations were slightly different. Our client was Delphi Win32, and at the time didn't have good support for JSON, so we had to use SOAP.
The client also didn't support nullable primitives, so the POCOs removed all unsupported types, and performed other changes to ensure interoperability, then we used Automapper custom mappings to handle the two way conversions.
All the WCF services (contracts and implementations) where also generated by T4 templates, using a generic repository. With T4 templates, I was able to generate a separate WCF service per table for CRUD operations, and then manually created WCF services that were business specific.
Finally, I was also able to used T4 templates to generate the Delphi repositories that interacted with the SOAP services.
Or
You could just as easily move the POCOs (and code generation) to a separate project, change your DataAccessLayer library to reference the POCOs library and only contain the Db context made up of DbSets of your POCOs, and Data access logic but no entities (which are now POCOs). Your clients will not need to have a dependency on the DataAccessLayer library.
So... a good solution, depending on your constraints.

Unity Lifetime Managers & EF Data Context --> Best Practice

All,
There has been a lot of posts about Unity Lifetime Managers but I have yet to find someone state a good rule of thumb for "in these cases you should always use X". Let me describe my application, I have an ASP.NET MVC 4 Web Application. I have a Visual Studio solution containing 3 projects, my 'Core' project which has all of my EF stuff, a testing project, and the MVC Web Project. I am using Unity for dependency injection and have the following code right now:
// Context
container.RegisterType<IDatabaseFactory, DatabaseFactory>(
new ContainerControlledLifetimeManager();
container.RegisterType<UnitOfWork>(
new ContainerControlledLifetimeManager());
However, I'm noticing that my context is not recreated with every new web request which is what I think I would want (let me know if I'm wrong in that assumption). I'm having a hard time analyzing all of the information from the sites listed below and have read about a lot of people creating their own class named PerHttpRequestLifetimeManager to handle this.
What truly is the best practice here?
Understanding Lifetime Managers by Microsoft's Developer Network - http://msdn.microsoft.com/en-us/library/ff660872(v=PandP.20).aspx
MVC DI & Unity with Lifetime Manager via CodeProject - http://www.codeproject.com/Articles/424743/MVC-DI-Unity-with-Lifetime-Manager
ASP.NET MVC Tip: Dependency Injection with Unity Application Block via Shiju Varghese's Blog - http://weblogs.asp.net/shijuvarghese/archive/2008/10/24/asp-net-mvc-tip-dependency-injection-with-unity-application-block.aspx
MVC, EF - DataContext singleton instance Per-Web-Request in Unity via Stack Overflow - MVC, EF - DataContext singleton instance Per-Web-Request in Unity
Inject same DataContext instance across several types with Unity via Stack Overflow - Inject same DataContext instance across several types with Unity
Yes, you usually want one DbContext per request.
A PerHttpRequestLifetimeManager or child container created on every request are the typical ways this is handled.
The latest release of Unity introduces the Unity bootstrapper for ASP.NET MVC which has a new built-in lifetime manager: PerRequestLifetimeManager.
You can read more in the Developer's Guide to Dependency Injection Using Unity chapter 3, Dependency Injection with Unity.

Where to put Service/Data Access Classes in a Zend Framework App

I originally wanted to find out how to access the Doctrine 2's Entity Manager from within Entity Classes. But I saw another question Using EntityManager inside Doctrine 2.0 entities, and learnt that I should be using a service class. I wonder where should I put in a Zend Framework Application? Also is it also called a DAO (Data Access Object)? I am thinking of naming it DAO instead of Service as Service sounds alot like something for external sites to use (like Web Service)?
I am thinking something like Application_Models_DAO_User?
Service classes are part of the autoloader mapping. Like Application_Model_Something can be found in application/models, it's the same for services.
An application service Application_Service_Something should be located at: application/services/Something.php
When you use service classes inside modules, for example Blog_Service_Something they need to be located at: application/modules/blog/services/Something.php
I think classes like entity managers shouldn't be part of your controllers nor your models, but located in service classes.