php - How to implement Depedency Injection correctly when injected service has required constructor argument - TagMerge
4How to implement Depedency Injection correctly when injected service has required constructor argumentHow to implement Depedency Injection correctly when injected service has required constructor argument

How to implement Depedency Injection correctly when injected service has required constructor argument

Asked 1 years ago
0
4 answers

You need to register your service in service provider. You can do it in AppServiceProvider or in custom provider.

//retrieve credentials from wherever you need to get them, ex: config file
$credentials = config('app.credentialts');

$this->app->bind(MyService::class, function ($app) use ($credentials) {
    return new MyService($credentials);
});

Check out Laravel Service Providers and Laravel Service Containers for more detailed information.

Source: link

0

>=RC.5
@NgModule({
  providers: [/*providers*/]
  ...
})
or for lazy loaded modules
static forRoot(config: UserServiceConfig): ModuleWithProviders {
  return {
    ngModule: CoreModule,
    providers: [
      {provide: UserServiceConfig, useValue: config }
    ]
  };
}
When a component or service requests a value from DI like
constructor(someField:SomeType) {}
DI looks up the provider by the type SomeType. If @Inject(SomeType) is added
constructor(@Inject(SomeType) someField:SomeType) {}
However there are situations where you want to customize the behavior for example to inject a configuration setting.
constructor(@Inject('someName') someField:string) {}

Source: link

0

A dependency is an object that another object depends on. Examine the following MessageWriter class with a Write method that other classes depend on:
public class MessageWriter
{
    public void Write(string message)
    {
        Console.WriteLine($"MessageWriter.Write(message: \"{message}\")");
    }
}
A class can create an instance of the MessageWriter class to make use of its Write method. In the following example, the MessageWriter class is a dependency of the Worker class:
public class Worker : BackgroundService
{
    private readonly MessageWriter _messageWriter = new MessageWriter();

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            _messageWriter.Write($"Worker running at: {DateTimeOffset.Now}");
            await Task.Delay(1000, stoppingToken);
        }
    }
}
As an example, the IMessageWriter interface defines the Write method:
namespace DependencyInjection.Example;

public interface IMessageWriter
{
    void Write(string message);
}
This interface is implemented by a concrete type, MessageWriter:
namespace DependencyInjection.Example;

public class MessageWriter : IMessageWriter
{
    public void Write(string message)
    {
        Console.WriteLine($"MessageWriter.Write(message: \"{message}\")");
    }
}
The sample code registers the IMessageWriter service with the concrete type MessageWriter. The AddScoped method registers the service with a scoped lifetime, the lifetime of a single request. Service lifetimes are described later in this article.
namespace DependencyInjection.Example;

class Program
{
    static Task Main(string[] args) =>
        CreateHostBuilder(args).Build().RunAsync();

    static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((_, services) =>
                services.AddHostedService<Worker>()
                        .AddScoped<IMessageWriter, MessageWriter>());
}

Source: link

0

Or, you could added using the NuGet command line or edit the *.csproj file directly, since this is perfectly acceptable in the .NET Core era.
<ItemGroup>
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="1.1.1" />
  </ItemGroup>

Source: link

Recent Questions on php

    Programming Languages