I am currently looking into Orleans as a backend for Asp.net core web api project, and was wondering if anyone has any experience with its new feature - "direct client". The orleans docs say "it allows co-hosting a client and silo in a way that let the client communicate more efficiently with not just the silo it's attached to, but the entire cluster", and I am aware that you can code something like this (and it works just fine in a console app):
var silo = new SiloHostBuilder()
.UseLocalhostClustering()
.EnableDirectClient()
.Build();
await silo.StartAsync();
var client = silo.Services.GetRequiredService<IClusterClient>();
I am struggling trying to figure out where to put this type of code in an asp.net project that has its own webhost builder in "Main" (should it go to Startup class in "ConfigureServices"?). In the end, we are aiming for a separate client/server setup, but for faster development it would be useful to play with a simple setup, which direct client appears to allow for. Any pointers to resources and/or sample solutions containing direct client with asp.net core would be appreciated. Thanks.
EDIT: Here's the code that kinda works for me now, but I am not happy with he way the DI is set up
public static async Task Main(string[] args)
{
var silo = new SiloHostBuilder()
.UseLocalhostClustering()
.ConfigureServices(services =>
{
services.AddDbContext<UserDbSet>(o => o.UseSqlite("Data Source=UserTest.db"));
services.AddMediatR(typeof(Startup).Assembly);
})
.EnableDirectClient()
.Build();
await silo.StartAsync();
var client = silo.Services.GetRequiredService<IClusterClient>();
await WebHost.CreateDefaultBuilder(args)
.UseConfiguration(new ConfigurationBuilder()
.AddCommandLine(args)
.Build())
.ConfigureServices(services =>
services
.AddSingleton<IGrainFactory>(client)
.AddSingleton<IClusterClient>(client))
.UseStartup<Startup>()
.Build()
.RunAsync();
}
If I put registration of the DbContext and Mediatr in the StartUp class, grain code fails with an exception indicating failure to instantiate the required dependencies. Maybe I am doing something wrong when setting up the Webhost?
For ASP.NET 2.x & Orleans below 2.3, I recommend creating & starting the silo before the Web host. When configuring the Web host, inject the IGrainFactory & IClusterClient instances from the silo (obtained via silo.Services):
var silo = new SiloHostBuilder()
.UseLocalhostClustering()
.EnableDirectClient()
.Build();
await silo.StartAsync();
var client = silo.Services.GetRequiredService<IClusterClient>();
var webHost = new WebHostBuilder()
.ConfigureServices(services =>
services
.AddSingleton<IGrainFactory>(client)
.AddSingleton<IClusterClient>(client))
.UseStartup<Startup>()
// Other ASP.NET configuration...
.Build();
For ASP.NET 3.0 & Orleans 2.3 or greater, the integration code becomes simpler due to the addition of Microsoft.Extensions.Hosting support in both frameworks:
var host = new HostBuilder()
.ConfigureWebHost(builder =>
{
// Adding IGrainFactory, etc, is not necessary, since Orleans
// and ASP.NET share the same dependency injection container.
builder.UseStartup<Startup>();
})
.UseOrleans(builder =>
{
// EnableDirectClient is no longer needed as it is enabled by default
builder.UseLocalhostClustering();
})
.Build();
await host.StartAsync();
Related
Looking for some examples on how to setup unit testing around IFunctionsWorkerMiddleware. All the examples I've found are for MVC and not function apps.
Example for MVC, but looking for .net 6 using function apps
using var host = await new HostBuilder() .ConfigureWebHost(webBuilder => { webBuilder .UseTestServer() .ConfigureServices(services => { services.AddMyServices(); }) .Configure(app => { app.UseMiddleware<MyMiddleware>(); }); }) .StartAsync(); var response = await host.GetTestClient().GetAsync("/")
Thanks in advance.
In order to test the middleware we need to spin up a host using HostBuilder; as part of configuring host builder we can stipulate it needs to use the test server (an in-memory webserver). This is what we will make request against an what should be executing the middleware. Every single example I've found and tried are all for MVC and nothing for function apps. and every attempt pretty much results in a gRPC issue (gRPC is spun uo by the function app process by default, I cannot find where/how to not set it up).
I would like to use ASP.NET Core's default DI container to setup DI for my Service Fabric project.
//This is what I've got so far, and it works great
ServiceRuntime.RegisterServiceAsync(
"MyServiceType",
context => new MyService(context, new MyMonitor()
).GetAwaiter().GetResult();
//This is how I use it
public MyService(StatefulServiceContext context, IMonitor myMonitor)
: base(context)
{
this._myMonitor = myMonitor;
}
How would I set up DI, if MyMonitor class has a dependency on a ConfigProvider class, like this:
public MyMonitor(IConfigProvider configProvider)
{
this._configProvider = configProvider;
}
I think this question will give you some light: Why does ServiceRuntime.RegisterServiceAsync return before the serviceFactory func completes?
Technically, the ServiceRuntime.RegisterServiceAsync() is a dependency registration, it requires you to pass the serviceTypeName and the factory method responsible for creating the services Func<StatelessServiceContext, StatelessService> serviceFactory
The factory method receives the context and returns a service (Stateful or stateless).
For DI, you should register all dependencies in advance and call resolve services to create the constructor, something like:
var provider = new ServiceCollection()
.AddLogging()
.AddSingleton<IFooService, FooService>()
.AddSingleton<IMonitor, MyMonitor>()
.BuildServiceProvider();
ServiceRuntime.RegisterServiceAsync("MyServiceType",
context => new MyService(context, provider.GetService<IMonitor>());
}).GetAwaiter().GetResult();
PS:
Never Register the context (StatelessServiceContext\StatefulServiceContext) in the DI, in a shared process approach, multiple partitions might be hosted on same process and will have multiple contexts.
This code snippet is not tested, I've used in the past, don't have access to validate if matches the same code, but is very close to the approach used, might need some tweaks.
Hi #OscarCabreraRodríguez
I am working on the project that simplifies development of Service Fabric Reliable Services and it has great built-in support for dependency injection scenarios.
You can find general information project page, wiki and specific information about dependency injection here.
The idea is that project abstracts you from working with Service instance directly instead providing you with a set of more concrete objects.
Here is a simple example for ASP.NET Core application:
public static void Main(string[] args)
{
new HostBuilder()
.DefineStatefulService(
serviceBuilder =>
{
serviceBuilder
.UseServiceType("ServiceType")
.DefineAspNetCoreListener(
listenerBuilder =>
{
listenerBuilder
.UseEndpoint("ServiceEndpoint")
.UseUniqueServiceUrlIntegration()
.ConfigureWebHost(
webHostBuilder =>
{
webHostBuilder
.ConfigureServices(
services =>
{
// You can configure as usual.
services.AddTransient<IMyService, MyService>();
})
.UseStartup<Startup>();
});
});
})
.Build()
.Run();
[Route("api")]
public class ApiController : Controller
{
public ApiController(IMyService service) { }
[HttpGet]
[Route("value")]
public string GetValue()
{
return $"Value from {nameof(ApiController)}";
}
}
Hope I understand your use case correctly and this information is relevant.
I created a basic Asp.net core 2.0 web application in the following way:
New Application => ASP.Net Core Web Application => Web Application =>
(MVC) => Change Authentication => Individual User Accounts (With docker enabled)
Debugging this will give you this:
This will obviously give you a 404, if you get rid of https://localhost:44360/ then the application is debugging there. I've seen this answer, but this didn't work for me.
I created a hosting.json as the answer suggested:
{
"server": "Microsoft.AspNetCore.Server.Kestrel",
"server.urls": "http://localhost:4000"
}
I added this to the Configure() method in startup:
var config = new ConfigurationBuilder()
.AddJsonFile("/app/hosting.json", optional: false)
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.Build();
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
This didn't fix my startup issue. What am I doing wrong or what do i need to do to fix this debug issue?
I was seeing the same issue after creating a new project and installing Docker for Windows with Visual Studio Community 2017.
It appears that the docker-compose Property Pages had a bad Service URL property, which in my case was generated as: http://localhost:{ServicePort}/https://localhost:44339/
To fix the issue:
Right-click the docker-compose project
Select Properties
Replace Service URL with: http://localhost:{ServicePort}
I am struggling to achieve the following:
I have created a Java websocket server which publishes data every 1 sec.
In ASP MVC projest I would like to receive the data and save them in database only so no JS involved here.
I am able to read the websocket data using console application method below :
using WebSocketSharp;
List<string> readoutList = new List<string>();
public void receiveMessage() {
using (var ws = new WebSocket("ws://localhost:4567/socket/"))
{
ws.OnMessage += (sender, e) =>
{
if (e.IsText)
{
readoutList.Add(e.Data.ToString());
Console.WriteLine(e.Data.ToString());
}
};
ws.Connect();
Console.ReadKey(true);
}
}`
How to create a service of this kind within the ASP MVC project? I need some direction here.
MVC is stateless so you have to request back to the server to initiate the request (such as from a form post) but within the MVC controller response, you can kick off the request to the server (as an example using a different technology). The problem is there isn't necessarily a 1 to 1 translation in MVC; initiating the request using client-side JavaSvcript would be the option here. Initiating these types of requests within MVC may cause issues with timeouts too that you have to be aware of.
OR, you can consider a scheduled windows program or a windows service that is installed, which can manage itself and initiate the request every so often. I think this is the better option.
I have an existing MVC application that is using Dependency Injection with Ninject. I installed the Ninject.MVC3 nuget package and it creates a class called NinjectWebCommon in my App_Start, which completely isolates the kernel and registers all of my bindings:
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
return kernel;
}
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IFoo>().To<Foo>();
}
We have a new requirement that we thought SignalR would be able to satisfy, so we installed SignalR 2 nuget package into the project. I created a Hub and did some searching on how to implement Dependency Injection into the project and found an article that suggests creating a SignalRDependencyResolver. http://www.asp.net/signalr/overview/signalr-20/extensibility/dependency-injection
The article has you creating a kernel in the Startup.cs file that is used for registering SignalR in OWIN:
public class Startup
{
public void Configuration(IAppBuilder app)
{
var kernel = new StandardKernel();
var resolver = new NinjectSignalRDependencyResolver(kernel);
kernel.Bind<IStockTicker>()
.To<Microsoft.AspNet.SignalR.StockTicker.StockTicker>() // Bind to StockTicker.
.InSingletonScope(); // Make it a singleton object.
kernel.Bind<IHubConnectionContext>().ToMethod(context =>
resolver.Resolve<IConnectionManager>().GetHubContext<StockTickerHub>().Clients
).WhenInjectedInto<IStockTicker>();
var config = new HubConfiguration()
{
Resolver = resolver
};
app.MapSignalR(config);
}
}
The problem is that this approach has me creating two different kernels and they seem to have their own set of dependencies that they know how to resolve. If I have a dependency defined in NinjectWebCommon, the Hub doesn't know how to resolve that dependency. Without exposing my kernel in NinjectWebCommon, what is the proper way to add DI into SignalR using the Ninject.MVC3 package?
None of the current answers directly answer your question. Also achieving the result you are after is very straightforward once you know exactly what to do. The "proper" way to do this is to set SignalR's dependency resolver in the CreateKernel method of the NinjectWebCommon class.
Assuming you have created a NinjectSignalRDependencyResolver class as you mention, no other code needs to be added anywhere except for the line highlighted in the code snippet below:
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
// THIS LINE DOES IT!!! Set our Ninject-based SignalRDependencyResolver as the SignalR resolver
GlobalHost.DependencyResolver = new NinjectSignalRDependencyResolver(kernel);
RegisterServices(kernel);
return kernel;
}
Apart from the above, nothing more needs to be done except declaring your bindings in the RegisterServices method of NinjectWebCommon. In your example this would look like:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IStockTicker>()
.To<Microsoft.AspNet.SignalR.StockTicker.StockTicker>() // Bind to StockTicker.
.InSingletonScope(); // Make it a singleton object.
kernel.Bind<IHubConnectionContext>().ToMethod(context =>
resolver.Resolve<IConnectionManager>().GetHubContext<StockTickerHub>().Clients
).WhenInjectedInto<IStockTicker>();
}
Except for the NinjectSignalRDependencyResolver class you created, no other code needs to be added. Importanly, the OwinStartup class remains unmodified, as follows:
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
The above example achieves the following important outcomes which were what you asked in your question:
You only have a single Ninject Kernel created
The kernel and all binding configurations remain confined to NinjectWebCommon
The default SignalR resolver is your NinjectSignalRDependencyResolver
Dependency Injection into all SignalR hubs is achieved
Hopefully this helps people out.
Have you tried adding the StockTickerHub itself to your kernel?
By default, SignalR uses Activator.CreateInstance to construct Hubs without any constructor arguments. If you want to inject your own dependencies into a Hub, you can do so by registering the Hub with SignalR's dependency resolver.
https://github.com/SignalR/SignalR/blob/2.0.1/src/Microsoft.AspNet.SignalR.Core/Hubs/DefaultHubActivator.cs#L28
If you want to get really creative, you can register your own IHubActivator instead of registering all of Hubs individually.
I go into more detail in how Hubs are created by default in this answer: SignalR with IoC (Castle Windsor) - which lifetime for hubs?
There is a problem with the singleton scope. I don´t know who should get the blame here (Ninject, SignalR, MVC, etc...), but it works if you use ToConstant:
var binding = Bind<IMustBeSingleton>().ToConstant(new MustBeSingleton());
I had the same problem, and I found the solution: SignalR, WebAPI and MVC sharing the same dependency resolver kernel
I shared a complete solution with MVC, WebAPI and SignalR using the same Ninject kernel: https://drive.google.com/file/d/0B52OsuSSsroNX0I5aWFFb1VrRm8/edit?usp=sharing
That example web app, contains a single page that shows the AppDomain and GetHashCode of an object that is supposed to be unique across the three frameworks, giving a result similar to:
Dependency Test
Framework IMySingletonService instance
MVC AppDomainId:2 / HashCode:5109846
WebAPI AppDomainId:2 / HashCode:5109846
SignalR AppDomainId:2 / HashCode:5109846
I hope this helps.