How do i inject a service to another service in Blazor? - asp.net

I have DataService and StateContainer.
DataService is responsible to obtain and provide data with respect to state changes. StateContainer is responsible as states changes, it registeres as a singleton.
I want DataService can access StateContainer public property. such that it could provide the data accordingly, How may I do so? How should I register DataService?

Just register your DataService in the DI System
builder.Services.AddSingleton<DataService>();
Now you should be able to Access the StateCointainer via DI if you inject it via the Constructor.
public class DataService
{
private readonly StateContainer _stateContainer;
public DataService(StateContainer stateContainer)
{
_stateContainer = stateContainer;
}
}

Related

Dependency injection in my singleton class .NET Core

I'm having trouble injecting the dependency I pass into the constructor of my Asegurador class.
When I want to instantiate, _instance = new Asegurador(); I don't have the parameter required by the constructor (IGeneralRepository), how can I solve this problem?
Note that my Asegurador class is a singleton.
private Asegurador(IGeneralRepository generalRepository)
{
_token = GetTokenAsync().Result;
_repository = generalRepository;
}
public static Asegurador Instance
{
get
{
if (_instance == null)
{
_local = System.Environment.GetEnvironmentVariable("SEGUROS_LOCAL") ?? "local";
_instance = new Asegurador();
}
return _instance;
}
}
When using a DI container you can (and should) let it take care of handling the Lifetime of a dependency.
.Net core's dependency injection lets you define 3 different lifetimes for your services (Docs):
Transient: a transient service is recreated each time it is injected
Scoped: a scoped service is created once for each request
Singleton: a singleton is created once in the whole application lifetime.
The best approach to achieve what you are trying to do is the following:
Amend your Asegurador class so that it has a public constructor and get rid of the static Instance property
public class Asegurador {
public Asegurador(IGeneralRepository generalRepository)
{
_token = GetTokenAsync().Result; //I know too few about it but I would try to pass it as a dependency as well
_repository = generalRepository;
}
}
instead of calling Asegurador.Instance inject the dependency in the client class
public class IUseTheAsegurador {
private Asegurador _asegurador;
public IUseTheAsegurador(Asegurador asegurador)
{
_asegurador = asegurador;
}
}
Register all in the DI in your Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSingleton<Asegurador>();
services.AddScoped<IUseAsegurador>(); //This can be Singleton or Transient as well, depending on your needs
...
}
I (a lot of people actually :D) prefer this approach because it leaves the responsability of guaranteeing a single instance to the DI and also because lets you write unit tests for the client class (IUseTheAsegurador in the example) in an easier way.

Symfony 4 - how dependecy injection works

Using Symfony 3.4 we call services like so: $container->get('service.name')
so we make sure to give names to our services.
in Symfony 4 we inject services by class name or interface directly in the controller like so:
public function someAction(HttpClientInterface $service){
// do something here
}
so what confuses me here is that we are injecting an interface and symfony takes care of invoking the right object in the controller.
my question is: if I have 2 services that implements the same interface :
class ClassA implements InterfaceX{}
class ClassB implements InterfaceX{}
and in the controller I do this:
public function someAction(InterfaceX $service){
// do something here
}
which service gets invoked ?
Yes, services can implement the same interface and in your controller you will need to inject correct service, like this:
public function someAction(ClassA $serviceA){
// do something here
}
and
public function someOtherAction(ClassB $serviceB){
// do something here
}
If you need same service in multiple methods on the same class, use Dependency Injection on the __construct

what is the relation between GenricServlet and ServletConfig?

A GenericServlet is a type of ServletConfig, also GenericServlet has a ServletConfig. What is logic in this? How should I understand this?
public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
private static final long serialVersionUID = 1L;
private transient ServletConfig config;
..
}
The ServletConfig is an interface and is implemented by services in order to pass configuration information to a servlet when it is first loaded.
GenericServlet implements ServletConfig. It's not a subclass of ServletConfig. Understand the difference between a subclass and interface.
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It provides the implementation of all the methods of these interfaces except the service method.
GenericServlet class can handle any type of request so it is protocol-independent.
You may create a generic servlet by inheriting the GenericServlet class and providing the implementation of the service method.
Visit here for more

Can I add a new scoped service within a custom middleware?

I'm using WebApi in Asp .Net Core and I'm wondering if/how I can add a new scoped service that all following middleware and controllers can get access to through dependency injection? Or should I share state with HttpContext.Items instead? That doesn't seem to be what it is intended for since HttpContext isn't available at all in a WebApi-controller?
If neither HttpContext or DI is the right tool for this, then how can I propagate state in the request-pipeline without having it already created from the beginning?
First add your scoped service in your ConfigureServices(IServiceCollection services)
services.AddScoped<IMyService, MyService>();
Then, the only way I know of to get a scoped service injected into your middleware is to inject it into the Invoke method of your Middlware
public class MyMiddleware
{
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext, IMyService service)
{
service.DoSomething();
await _next(httpContext);
}
}
Injecting in the constructor of MyMiddleware will make it a singleton by default as it's only called on startup. Invoke is called every time and dependency injection will grab the scoped object.

In Web API 2.2: How to use the dependency injector when needed?

I have a question for the article, which probably many of us have read: Dependency Injection in ASP.NET Web API 2.
Let's assume, that the ProductRepository at some later point in time needs to delegate to some other service. How should ProductRepository request the concrete instance from the dependency injector at that later time as it is a bad practice to inject the dependency injector itself into the ProductRepository?
You can inject the new service inside the ProductRepository just like you injected the IProductRepository into ProductsController.
public class ProductRepository : IDisposable
{
private readonly IOtherService m_OtherService;
public ProductRepository(IOtherService other_service)
{
m_OtherService = other_service;
}
...
}
If you register IOtherService successfully in the container, the container would be able to create ProductRepository and ProductsController successfully.
If it is a problem for you to have the OtherService created everytime (maybe you will not use it all the time), you can use the factory pattern. For example:
public interface IOtherServiceFactory
{
IOtherService Create();
}
public class ProductRepository : IDisposable
{
private readonly IOtherServiceFactory m_OtherServiceFactory;
public ProductRepository(IOtherServiceFactory other_service_factory)
{
m_OtherServiceFactory = other_service_factory;
}
...
}
Now, you can create an instance of OtherService only when you need it.
You have to create an implementation of IOtherServiceFactory and register it with the container.

Resources