Clients.All, Clients.Caller and Clients.Others throwing TypeLoadException - asp.net-core-signalr

I have a simple Typed Hub setup through an interface. I can successfully connect to the SignalR Hub.
namespace POC.WebSocket
{
public class ApiResultHub : Hub<IApiResultHubClient>
{
public async Task SendMessage(string user, string message)
{
await Clients.All.ReceiveMessage(user, message);
}
public override Task OnConnectedAsync()
{
Clients.Caller.ReceiveMessage("newUser", $"{Context.ConnectionId}");
return base.OnConnectedAsync();
}
}
}
However, when I try invoke a client side hub method it throws the following exception:
Here are my other class files:
Startup.cs
namespace POC.WebSocket
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder
.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins("https://localhost:44324", "https://localhost:44326")
.AllowCredentials();
}));
services.AddSignalR();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors("CorsPolicy");
app.UseSignalR(routes =>
{
routes.MapHub<ApiResultHub>("/apiResult");
});
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
IApiResultHubClient`T.cs
namespace POC.Common
{
public interface IApiResultHubClient
{
Task ReceiveMessage(string user, string message);
Task SendApiResponse<T>(ApiResult<T> data);
}
}
Has anyone else seen this issue? I saw few similar issues with being able to connect to the hub itself. However, as mentioned I am able to successfully connect to the hub, just not able to resolve Clients.All, Clients.Caller or Clients.Others.
All libraries updated today:
.Net Core version 2.1.4
.Net SignalR Core version 1.0.3
Edits:
Found details of the exception:
Method 'SendApiResponse' in type
'Microsoft.AspNetCore.SignalR.TypedClientBuilder.IApiResultHubClientImpl'
from assembly 'Microsoft.AspNetCore.SignalR.TypedClientBuilder,
Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have
an implementation.

Related

Blazor Server (EF Core) and database connection

Sorry for the rudimentary question.
I'm currently studying application development with Blazor Server and am having trouble connecting to a database.
I'm trying to use DI to connect to the database.
I created a code that uses the factory pattern as shown below, but an error occurs in the part that gets the connection string.
public void ConfigureServices(IServiceCollection services)
{
//error:CS0121 Inappropriate call between the following methods or properties: 'Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.AddDbContextFactory<TContext>(Microsoft.Extensions.DependencyInjection.IServiceCollection, System.Action<Microsoft.EntityFrameworkCore.DbContextOptionsBuilder>, Microsoft.Extensions.DependencyInjection.ServiceLifetime)' と 'BlazorSv.Models.FactoryExtensions.AddDbContextFactory<TContext>(Microsoft.Extensions.DependencyInjection.IServiceCollection, System.Action<Microsoft.EntityFrameworkCore.DbContextOptionsBuilder>, Microsoft.Extensions.DependencyInjection.ServiceLifetime)'
services.AddDbContextFactory<BlazorSv.Models.SQLbeginnerContext>(options => options.UseNpgsql(Configuration.GetConnectionString("DBConnection")));
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
}
I thought that the definition of the <Models.SQLbeginnerContext> part was ambiguous, so I wrote the hierarchy, but it didn't work.
What should I do about this error?
I want some advice
Below is SQLbegginerContext.cs that describes StartUp.cs and the factory pattern.
StartUp.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
//error:CS0121 Inappropriate call between the following methods or properties: 'Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.AddDbContextFactory<TContext>(Microsoft.Extensions.DependencyInjection.IServiceCollection, System.Action<Microsoft.EntityFrameworkCore.DbContextOptionsBuilder>, Microsoft.Extensions.DependencyInjection.ServiceLifetime)' と 'BlazorSv.Models.FactoryExtensions.AddDbContextFactory<TContext>(Microsoft.Extensions.DependencyInjection.IServiceCollection, System.Action<Microsoft.EntityFrameworkCore.DbContextOptionsBuilder>, Microsoft.Extensions.DependencyInjection.ServiceLifetime)'
services.AddDbContextFactory<Models.SQLbeginnerContext>(options => options.UseNpgsql(Configuration.GetConnectionString("DBConnection")));
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
SQLbegginerContext.cs
public interface IDbContextFactory<TContext> where TContext : DbContext
{
TContext CreateDbContext();
}
public class blazordbFactory<TContext> : IDbContextFactory<TContext> where TContext : DbContext
{
public blazordbFactory(IServiceProvider provider)
{
this.provider = provider;
}
private readonly IServiceProvider provider;
public TContext CreateDbContext()
{
return ActivatorUtilities.CreateInstance<TContext>(provider);
}
}
public static class FactoryExtensions
{
public static IServiceCollection AddDbContextFactory<TContext>(
this IServiceCollection collection,
Action<DbContextOptionsBuilder> optionsAction = null,
ServiceLifetime contextAndOptionsLifetime = ServiceLifetime.Singleton)
where TContext : DbContext
{
collection.Add(new ServiceDescriptor(
typeof(IDbContextFactory<TContext>),
sp => new blazordbFactory<TContext>(sp),
contextAndOptionsLifetime));
collection.Add(new ServiceDescriptor(
typeof(DbContextOptions<TContext>),
sp => GetOptions<TContext>(optionsAction, sp),
contextAndOptionsLifetime));
return collection;
}
private static DbContextOptions<TContext> GetOptions<TContext>(
Action<DbContextOptionsBuilder> action,
IServiceProvider sp = null) where TContext : DbContext
{
var optionsBuilder = new DbContextOptionsBuilder<TContext>();
if (sp != null)
{
optionsBuilder.UseApplicationServiceProvider(sp);
}
action?.Invoke(optionsBuilder);
return optionsBuilder.Options;
}
}
public partial class SQLbeginnerContext : DbContext
{
public SQLbeginnerContext()
{
}
public SQLbeginnerContext(DbContextOptions<SQLbeginnerContext> options)
: base(options)
{
}
追記:SQLbegginer.cs
//Comment out this part
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseNpgsql("Host=localhost; Database=SQLbeginner; Username=user; Password=****")
}
}

Replacing CastleWindsor with Autofac in .NETCore3.1

I was using CastleWindsor in my ASP.NETCore2.2 WebAPI project and was working fine. I'm migrating to ASP.NETCore3.1 now and it doesn't look like CastleWindor has offical support for that so I decided to move to Autofac with minimal changes but having some issues resolving the dependencies.
In my project, I've maintained very loose coupling between different layers in the application namely, business layer, data layer, and translation layer. All of those layers are in their own assemblies. And then in my main project, I've a folder say "dependencies" which will hold all the DLLs of differnet layers. Additionally, I've a separate project that lists all the interfaces that are implemented by the different layers and which needs to be resolved by the IoC container.
The project having all the interfaces looks like this:
namespace Shared.Interfaces
{
public interface IBusinessLayer<T>
{
....
}
public interface IDataLayer<T>
{
....
}
public interface ITranslationLayer<T>
{
....
}
}
The implementing projects looks like this:
namespace POC.Person.BusinessLayer
{
public class BusinessLayer<T> : IBusinessLayer<T> where T : Models.Person
{
...
}
}
namespace POC.Person.DataLayer
{
public class DataLayer<T> : IDataLayer<T> where T : Models.Person
{
...
}
}
namespace POC.Person.TranslationLayer
{
public class TranslationLayer<T> : ITranslationLayer<T> where T : Models.Person
{
...
}
}
Using Autofac in my migrated .netcore3.1 project, Startup.cs looks like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
//and other codes
}
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterModule(new DependencyResolver());
}
DependencyResolver is a class that inherits from Autofac.Module, which is again in a separate assembly in different project which looks like this:
namespace IOC.Autofac
{
public class DependencyResolver: Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
// get our path to dependencies folder in the main project
var path = Directory.GetCurrentDirectory() + "\\dependencies\\";
//get all the assemblies inside that folder
List<Assembly> assemblies = new List<Assembly>();
foreach (string assemblyPath in Directory.GetFiles(path, "*.dll", SearchOption.AllDirectories))
{
var assembly = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath);
assemblies.Add(assembly);
}
// Register and resolve the types with the container
builder
.RegisterAssemblyTypes(assemblies.ToArray())
.AsClosedTypesOf(typeof(IBusinessLayer<>))
.AsClosedTypesOf(typeof(IDataLayer<>))
.AsClosedTypesOf(typeof(ITranslationLayer<>))
.AsImplementedInterfaces()
.InstancePerRequest();
}
}
}
I'm getting this error and I've not been able to fix it:
":"Unable to resolve service for type 'Shared.Interfaces.IBusinessLayer`1[Models.Person]' while attempting to activate 'POC.Person.Controllers.PersonController'.","
Inside my controller I've injection which looks like this:
namespace POC.Person.Controllers
{
public class PersonController : ControllerBase
{
private readonly IBusinessLayer<Models.Person> _bl;
public PersonController(IBusinessLayer<Models.Person> bl)
{
_bl = bl;
}
//other codes
}
}
Program.cs looks like this:
namespace POC.Person
{
public class Program
{
public static void Main(string[] args)
{
var host = BuildWebHost(args);
host.Build().Run();
}
public static IHostBuilder BuildWebHost(string[] args)
{
return Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseKestrel()
.UseStartup<Startup>()
.UseIIS()
.UseIISIntegration();
;
}).ConfigureAppConfiguration((context, config) =>
{
var builtConfig = config.Build();
});
}
}
}
It looks like with autofac involving generics, registering and resolving the type is not that straight forward?
Autofac does not currently support registering open generics whilst assembly scanning. It's a long-running known issue. You can do assembly scanning, you can register open generics, you can't do both at the same time. There are some ideas in that linked issue on ways some folks have solved it.
Out of the box, the scanning logic would, thus, be reduced to:
builder
.RegisterAssemblyTypes(assemblies.ToArray())
.AsImplementedInterfaces()
.InstancePerRequest();
You need to register generics separately, like:
builder
.RegisterGeneric(typeof(TranslationLayer<>))
.As(typeof(ITranslationLayer<>));

ASP.NET Core 2.2 How to add two constructors to the same class using dependency injection?

I have a class "ConnectorManagement" in which I need to use both SignalR services as well as querying a db table using EF CORE.
I cant work out how to load both dbcontext and hubcontext into the same class using a constructor and dependancy injection. The current result is visual studio fails to load the project when run in debug. Tried researching this but not understanding what needs to be done.
Current code below:
namespace myNamespace.Controller
{
public class ConnectorManagement : IHostedService
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(Logger));
private readonly IHubContext<MessageHub> _hubContext;
public readonly ApplicationDbContext _context;
public ConnectorManagement(IHubContext<MessageHub> hubContext, ApplicationDbContext context)
{
_hubContext = hubContext;
_context = context;
}
public Task StartAsync(CancellationToken cancellationToken)
{
log.Info("Initial Test");
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
dbcontext class:
namespace myNamespace.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<myProject.Models.ConnectorInbound> ConnectorInbound { get; set; }
public DbSet<myProject.Models.ConnectorOutbound> ConnectorOutbound { get; set; }
public DbSet<myProject.Models.SystemMapping> SystemMapping { get; set; }
}
}
startup class:
namespace myProjectNamespace
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();
// Start up the TcpServerTcpServer engine
services.AddHostedService<ConnectorManagement>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSignalR();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseSignalR(routes =>
{
routes.MapHub<MessageHub>("/messageHub");
});
loggerFactory.AddLog4Net();
app.UseMvc();
}
}
}
I wasn't paying attention to the fact that you're injecting this into a hosted service. Hosted services are singletons and both the hub context and database context are scoped services. You need to inject IServiceProvider instead and then create a scope. This will need to be done for every usage; you cannot persist it on an ivar, for example. You can only use it within the using statement.
using (var scope = _serviceProvider.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
// Do something
}

How do you construct Entity Framework Core IdentityDbContext<> outside of a service?

I was curious as generally you can do this WITHOUT IdentityDbContext:
public class SomeContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
//I am using Postgres but will also accept answers to SQL Server as I want both ultimately
optionsBuilder.UseNpgsql(#"Host=localhost;Database=someDb;Username=user;Password=yeah");
}
}
}
But when I go to the 'IdentityDbContext<(POCOUser)>' my OnConfiguring method disappears. And it appears this is really not wired up anymore except if I am starting up a service and doing something similar to the Startup of:
services.AddDbContext<SomeContext>(cfg =>
{
cfg.UseSqlServer(_config.GetConnectionString("MyConnectionString"));
});
That's great if I am doing a service and the EF Core is in the same contained project. But what if I am not? Are you not able to specify the connection string on the fly in a constructor or other method on instantiation?
appsettings.json - add connection string:
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"SomeDatabase": "Host=localhost;Database=...;Username=...;Password=..."
}
}
Update Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services
.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);
services
.AddEntityFrameworkNpgsql()
.AddDbContext<SomeContext>(options => options.UseNpgsql(Configuration.GetConnectionString("SomeDatabase")))
.BuildServiceProvider();
}
Inject into controller:
private SomeContext _db;
public SomeController(SomeContext someContext)
{
_db = someContext;
}

get_CurrentTransaction in InMemory.TransactionManager does not have an implementation

I'm working on a .NET Core application that implements the InMemoryDatabase for integration testing. I'm following the instructions from this link.
Basically it shows how to configure the service (in Startup.cs) using the AddDbContext method which is what I did and I make the call to UseInMemoryDatabase:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options => options.UseInMemoryDatabase());
services.AddMvc();
services.AddSingleton<ITodoRepository, TodoRepository>();
services.AddScoped<IAssetRepository, AssetRepository>();
}
My AppDbContext is defined in another project in the solution and is defined as such:
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> dbContextOptions) :
base(dbContextOptions)
{
}
public DbSet<Asset> Assets { get; set; }
public DbSet<TodoItem> Todos { get; set; }
}
Back to the Startup.cs file, according to the link I need to code the Configure method like this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
var repository = app.ApplicationServices.GetService<IAssetRepository>();
InitializeDatabaseAsync(repository).Wait();
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
This snippet runs ok and executes the call to GetService. This call runs the constructor for AppDbContext but the constructor crashes with the folling exception. It crashes when calling the base constructor: base(dbContextOptions).
Method 'get_CurrentTransaction' in type
'Microsoft.EntityFrameworkCore.Storage.Internal.InMemoryTransactionManager'
from assembly 'Microsoft.EntityFrameworkCore.InMemory,
Version=1.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'
does not have an implementation.
I can't seem to figure out what is causing this exception. Can someone give me some direction?
Thanks !
After some more investigating, I found out that this error occurred because the project that contains the configuration code (Startup.cs) had a reference to version 1.0.1 of "Microsoft.EntityFrameworkCore.InMemory".
However, I changed it to 1.1.0 and it suddenly worked. So I'm assuming that the implementation was added to version 1.1.0.
Hope this helps anyone in the future.