How to use .net6 to operate redis? - asp.net-core

I upgraded to the latest .net6 version, but how to configure the connection service, I can't find the entry. Can I still use the previous Startup.cs configuration in .net6? Any help is greatly appreciated!I have read the documentation, but it didn't help me:https://learn.microsoft.com/en-us/dotnet/core/compatibility/6.0

1. You can register redis service like below.
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "jason******FebB5A=,ssl=True,abortConnect=False";
});
And you can use redis in your controller, like below:
public HomeController(ILogger<WeatherForecastController> logger, CosmosClient client,IDistributedCache distributedCache)
{
_logger = logger;
_client = client;
_distributedCache = distributedCache;
}
And the test result like below:

Related

ADVICE NEEDED: Real Time responsive Pub/Sub pattern for ASP.NET Core Razor pages

I am mandated to research on the pub/sub pattern to enable real time alerts for a Micro-Service architecture and trying to get it to work on docker using redis and .net core razor pages 7.0
HISTORY
Prior to this, we were using signalR, in .net FRAMEWORK, but now redesigning the entire application in .net core and moving away from a single dependency
OBJECTIVES
We want to use Redis and the default InMemoryCacheServices as our temp database, and a mixture of Redis pub/sub, Kafka, RabbitMQ.
WHAT I HAVE ARCHIVED
I have redis running on docker locally and can send realtime messages via console apps with the code below.
MY QUESTIONS
Does anyone know how this works ? ie make the front end responsive ?
The onGet() method below returns the value in the console app, but a boolean in the razor page
Or if I am going down the wrong direction, can anyone point me into the necessary patterns and technologies to be implemented ?
thank you
// ................... PROGRAM.CS In .net 7.0 ....................................//
var redis = ConnectionMultiplexer.Connect(configurationOptions);
ISubscriber subScriber = redis.GetSubscriber();
builder.Services.AddScoped(s => redis.GetDatabase());
// ................... CONSTRUCTOR ....................................//
private readonly ILogger<IndexModel> _logger;
private readonly IDatabase _database;
public IndexModel(ILogger<IndexModel> logger,IDatabase database)//, ISubscriber isubscribe)
{
_database = database;
_logger = logger;
}
// ................... OnGet method ....................................//
public void OnGet()
{
var configurationOptions = new ConfigurationOptions
{
EndPoints = { { "localhost", 32768 } },
AbortOnConnectFail = false, ,
ConnectTimeout = 10000
};
// I had manually hard coded the Redis connection to step through the code to see the returning values
var redis = ConnectionMultiplexer.Connect(configurationOptions);
ISubscriber subScriber = redis.GetSubscriber();
var pubSub = redis.GetSubscriber();
ViewData["message"] = pubSub.SubscribeAsync("MyKey", (channel, message) => MessageAction(message));
ViewData["message2"] = _database.StringGetAsync("MyKey").ToString();
}
private void MessageAction(RedisValue message)
{
ViewData["message3"] = message;
}
I have tried the above code
I am expecting to get a responsive UI in .net core razor pages

GetRequiredService from within Configure

I'm trying to access one of my services from within the Configure call within Startup.cs in aspnet core. I'm doing the following however I get the following error "No service for type 'UserService' has been registered." Now I know it is registered because I can use it in a controller so I'm just doing something wrong when it comes to using it here. Please can someone point me in the right direction. I'm happy with taking a different approach to setting up Tus if there's a better way of achieving what I want.
var userService = app.ApplicationServices.GetRequiredService<UserService>();
userService.UpdateProfileImage(file.Id);
The below is where I'm wanting to use
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
... Other stuff here...
app.InitializeSimpleInjector(container, Configuration);
container.Verify();
app.UseTus(httpContext =>
{
var restaurantEndpoint = "/restaurant/images";
var userEndpoint = "/account/images";
var endPoint = "/blank/images";
if (httpContext.Request.Path.StartsWithSegments(new PathString(restaurantEndpoint)))
{
endPoint = restaurantEndpoint;
}
if (httpContext.Request.Path.StartsWithSegments(new PathString(userEndpoint)))
{
endPoint = userEndpoint;
}
return new BranchTusConfiguration
{
Store = new TusDiskStore(#"C:\tusfiles\"),
UrlPath = endPoint,
Events = new Events
{
OnBeforeCreateAsync = ctx =>
{
return Task.CompletedTask;
},
OnCreateCompleteAsync = ctx =>
{
return Task.CompletedTask;
},
OnFileCompleteAsync = async ctx =>
{
var file = await ( (ITusReadableStore)ctx.Store ).GetFileAsync(ctx.FileId, ctx.CancellationToken);
var userService = app.ApplicationServices.GetRequiredService<UserService>();
userService.UpdateProfileImage(file.Id);
}
}
};
});
... More stuff here...
};
My end goal is to move this to an IApplicationBuilder extension to clean up my startup.cs but that shouldn't affect anything if it's working from within startup.cs
Edit: Add to show the registration of the userService. There is a whole lot of other stuff being registered and cross wired in the InitializeSimpleInjector method which I've left out. can add it all if need be..
public static void InitializeSimpleInjector(this IApplicationBuilder app, Container container, IConfigurationRoot configuration)
{
// Add application presentation components:
container.RegisterMvcControllers(app);
container.RegisterMvcViewComponents(app);
container.Register<UserService>(Lifestyle.Scoped);
container.CrossWire<IServiceProvider>(app);
container.Register<IServiceCollection, ServiceCollection>(Lifestyle.Scoped);
}
Please read the Simple Injector integration page for ASP.NET Core very closely, as Simple Injector integrates very differently with ASP.NET Core as Microsoft documented how DI Containers should integrate. The Simple Injector documentation states:
Please note that when integrating Simple Injector in ASP.NET Core, you do not replace ASP.NET’s built-in container, as advised by the Microsoft documentation. The practice with Simple Injector is to use Simple Injector to build up object graphs of your application components and let the built-in container build framework and third-party components
What this means is that, since the built-in container is still in place, resolving components using app.ApplicationServices.GetRequiredService<T>()—while they are registered in Simple Injector—will not work. In that case you are asking the built-in container and it doesn't know about the existence of those registrations.
Instead, you should resolve your type(s) using Simple Injector:
container.GetInstance<UserService>()

Adding SignalR service as a singleton and then adding redis to it

Hello i have an app up and running using orleans and signalR and i use a HubConnectionBuilder to initialize my SignalRClient like this
public async Task<HubConnection> InitSignalRCLient()
{
Program.WriteConsole("Starting SignalR Client...");
var connection = new HubConnectionBuilder()
.ConfigureLogging(logging =>
logging
.AddProvider(new LogProvider(Log.logger, new LogProviderConfiguration
{
Category = LogCategory.SignalR,
Level = LogLevel.Warning
}))
)
.WithUrl(Configuration.GetConnectionString("SignalRInterface"))
.Build();
And then i add the service as a singleton in the configure service
services.AddSingleton(SignalRClient)
The problem is now that i want to use redis as a backplane to this and i am having issues adding the redis service to my current way of using SignalR
like this doesn't work
services.AddSingleton(SignalRClient).AddStackExchangeRedis();
according to the documentation https://learn.microsoft.com/en-us/aspnet/core/signalr/redis-backplane?view=aspnetcore-2.2 it wants you to add it like
services.AddSignalR().AddStackExchangeRedis("<your_Redis_connection_string>");
but that doesn't work with how i use SignalR. Is there anyway to get my implementation to work or anyone got any advice on how to tackle this?
Try to add in ConfigureServices this:
services.AddDistributedRedisCache(option =>
{
option.Configuration = Configuration.GetConnectionString(<your_Redis_connection_string>);
});
services.AddSignalR().AddStackExchangeRedis(Configuration.GetConnectionString(<your_Redis_connection_string>));
Also add this in Configure
app.UseSignalR(routes =>
{
routes.MapHub<your_Hub>("/yourHub");
});
And don't forget add abortConnect=False in connectionStrings

How to seed Hangfire database in asp.net core 2.0

I'm trying to integrate "Hangfire" to my existing ASP.NET Core application. Looking into the documentaion, looks like the Hangfire db needs to be created if we want to use SQL Server storage option. But it would be really annoying to create a db every time we spin up a new server.
Is there a way I could seed DB with the SQL Storage option enabled rather than from startup class like this?
services.AddHangfire(options =>
options.UseSqlServerStorage(Configuration["HangfireConnection"]));
A good solution could be to isolate this concern to some TSQL scripts and run those scripts when the app startup or before running your tests (based on your scenario), but a quick solution that I have used before is something like this (based on this post).
public class HangfireContext : DbContext
{
public HangfireContext(DbContextOptions options)
: base(options)
{
Database.EnsureCreated();
}
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
var connectionString = Configuration.GetConnectionString("HangfireConnectionString");
var optionsBuilder = new DbContextOptionsBuilder<HangfireContext>();
optionsBuilder.UseSqlServer(connectionString);
var hangfireDbContext = new HangfireContext(optionsBuilder.Options);
services.AddHangfire(config =>
config.UseSqlServerStorage(connectionString));
}
}

How to configure NServiceBus with two RavenDB IDocumentStores?

In NSB 5, how do I correctly configure NSB with autofac container with one IDocumentStore for NSB data and a separate IDocumentStore for application data? I've pasted the relevant part of EndpointConfig below:
// Raven DataStore for Freight system
var appDataStore = new DocumentStore {
ConnectionStringName = "RavenDB",
DefaultDatabase = "ApplicationData"
};
appDataStore .Initialize();
// Raven DataStore for NServiceBus
var nsbDataStore = new DocumentStore
{
ConnectionStringName = "NServiceBus.Persistence",
DefaultDatabase = "BookingProcessing"
};
nsbDataStore.Initialize();
// Set up and build AutoFac container
var builder = new ContainerBuilder();
builder.RegisterInstance<DocumentStore>(appDataStore ).As<IDocumentStore>().SingleInstance();
var container = builder.Build();
// Set up NServiceBus
configuration.UseContainer<AutofacBuilder>(customizations => customizations.ExistingLifetimeScope(container));
configuration.UsePersistence<RavenDBPersistence>().SetDefaultDocumentStore(nsbDataStore);
I know this isn't working since I had problems storing sagas in another question. The SagaPersister tried to persist saga in appDataStore, but the Timeout Messages was persisted in nsbDataStore.
This issue is now fixed in NServiceBus.RavenDB v2.0.1
This is a sample for 4.x using unit of work,
If you use
Look here to see how you can implement IManageUnitsOfWork
The Init is here
Look here for the usage
will this help?