DotNet Core Dependency Injection Multiple Projects - asp.net-core

I am building a Blazor WASM application.
The application is working but I am now looking to split the project into sensible self contained projects but having a problem working out how to implement the dependency injection without creating a circular dependency between projects.
Projects:
App.Client - UI Razor Pages
App.Server - Main project, controllers, defines interfaces
App.Shared - Shared models between Client & Server
App.Data - Implements repositories, unit of work, Db Context, migrations
The problem I am having is that the App.Data project has a dependency on the App.Server project to implement the interfaces it requires, but then I am not sure how to configure the dependencies in the startup.cs file in the App.Server project as this cannot have a dependency on the App.Data project.

Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Test.Models;
using Test.Models.Data;
namespace Test
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
...
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("database"), b => b.MigrationsAssembly("Test")));
services.AddIdentity<User, Role>()
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IAntiforgery antiforgery)
{
...
}
}
}
Project structure

I ended up combining the two comments to implement a Clean Architecture structure modified for the Blazor WASM application.
Adding a Core project, defining the interfaces, and Infrastructure project implementing infrastructure interfaces such as the database. Server then has dependencies on these 2 projects which makes sense.
Startup then configures the interfaces via DI, using the appropriate implementations either in Core or Infrastructure.

Related

Build error when using [FromService] decorators in controller with Functions v3

I have created a new projected, where I am trying to use [FromServices] with Microsoft.NET.Sdk.Functions" Version="3.0.13" and "Microsoft.Azure.Functions.Extensions" Version="1.1.0".
There are some tickets opened on this subject. For example this one.
I haven't seen any response/solution from Microsoft.
Is there an incompatibility between libs, what is the combination that I should use?
If this method injection doesn't work, can you please tell me what other alternatives do I have?
Startup.cs
using Azure.Storage.Blobs;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
[assembly: FunctionsStartup(typeof(Startup))]
namespace SubscriptionManager.Functions
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddTransient<IAccountService, AccountService>();
builder.Services.AddScoped<ISubscriptionService, SubscriptionService>();
}
}
}
Thank you!
The .Net version comaptible with "Microsoft.Azure.Functions.Extensions" Version="1.1.0" is .NETStandard 2.0.
Please refer the Document.

How to get ConnectionString in a ClassLibrary?

Connection strings exist in appsettings.json in an ASP.Net MVC Core Project. I also have a Class Library Project in the same solution and there I want to get the connection string of web project, I am unable to find help in official resources, how can I achieve this?
Update: The class library is of .Net 4.6.1, also in the ASP.Net Core Project I am targeting .Net 4.6.1.
Register Configuration in Startup.cs
public void ConfigureServices(IServicesCollection services)
{
services.AddSingleton(Configuration);
}
Then you can inject it in controller or any other library project class
public HomeController(IConfigurationRoot Configuration)
{
this.Configuration= Configuration;
}
Then you can get connection string as you get in Startup.cs
Configuration.GetConnectionString("DefaultConnection")

ConnectionString from appsettings.json in Data Tier with Entity Framework Core

I have a new application that I am building on ASP.NET Core with Entity Framework Core. The application has a UI, model, business, and data tier. In previous versions of ASP.NET, you could set the connection string in the web.config and it would be available in referenced tiers by default. This does not appear to be the same case in ASP.NET Core with appsettings.json (or other config options)? Any idea on how this is accomplished? I have the dbcontext configured in the data layer, but I am current hard-coding the connection string.
All examples I have see out there has the dbcontext configured in the UI layer in startup.cs. This is what I am trying to avoid.
The question Here got off topic.
You can easily add an extension method of IServiceCollection into your business/services layer and use it to register its own dependencies. Then in the startup you just call the method on the service layer without having any reference to EntityFramework in your web app.
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace your.service.layer
{
public static class MyServiceCollectionExtensions
{
public static IServiceCollection AddMyServiceDependencies(this IServiceCollection services, string connectionString)
{
services.AddEntityFrameworkSqlServer()
.AddDbContext<YourDbContext>((serviceProvider, options) =>
options.UseSqlServer(connectionString)
.UseInternalServiceProvider(serviceProvider)
);
return services;
}
}
}
Startup:
using your.service.layer;
public void ConfigureServices(IServiceCollection services)
{
var connectionString = Configuration.GetConnectionString("EntityFrameworkConnectionString");
services.AddMyServiceDependencies(connectionString);
}
Now your web app only needs a reference to your business/service layer and it is not directly dependent on EntityFramework.

Using ninject dependecyResolver for both MVC and WebAPI

I have created and MVC 4 web application and decided to use web api in this app.
I'm using ninject dependency resolver for MVC web app. and now I want to use this ninject dependency resolver for web api.
but the problem raise here mvc IDependencyResolver namespace is: using System.Web.Mvc
and web api IDependencyResolver is using System.Web.Http.Dependencies
so how can I solve this issue?
finally I want something like this:
// Use the container and the NinjectDependencyResolver as
// application's resolver
var resolver = new NinjectDependencyResolver(container);
//Register Resolver for MVC
DependencyResolver.SetResolver(resolver);
//Register Resolver for Web Api
GlobalConfiguration.Configuration.DependencyResolver = resolver;
There is a way to share same container between MVC and ASP.NET Web API.
You just need to implement both interfaces.
public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver, System.Web.Mvc.IDependencyResolver
{
private readonly IKernel kernel;
public NinjectDependencyResolver(IKernel kernel)
: base(kernel)
{
this.kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(this.kernel.BeginBlock());
}
}
Check this article for solution:
Simple Way to share Dependency Resolvers between MVC and Web API
There is a NuGet package that does this. Add the NInject, NInject.Web.Common, NInject.MVCx and WebApiContrib.IoC.Ninject NuGet packages to your project. A NInjectWebCommon class should have been created in the App_Start folder. Add your binding for your dependencies to the RegisterServices method. In the CreateKernel method after the RegisterServices(kernel) call, add the following line:
GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel);
This will let you create the Ninject dependency resolver without having to create your own override class. Easy, right?

SignalR 2.0 The namespace '' already contains a definition for 'Startup'

I tried to follow a tutorial on SignalR 2.0. with ASP.NET MVC 4.0
I build the new Startup class as instructed.
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(MyApp.Startup))]
namespace MyApp
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
app.MapSignalR();
}
}
}
When I tried to build the project. I got The namespace 'MyApp' already contains a definition for 'Startup' .
I have search the whole project and physical folders to find where the second Startup,cs is but I could not find it.
Can anyone share some light on this?
Thanks,
I found the duplicate. It was defined in BundleConfig.cs. Removed it from BundleConfig.cs and it builds fine. Thanks,
Try making your Startup class partial:
public partial class Startup