Reputation: 1776
I am now using this in my register services section. The problem here is the my services have their own dependencies, and maybe those will have dependencies. I dont see how I can solve that problem with this. for instance my location service requires the http client, the logger and two different repositories. I was expecting that having already registered those 4 dependencies as services, this would sort of take care of itself. Any suggestion would be massively appreciated.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// db related
var connectionString = Configuration.GetConnectionString("VoloDataBaseConnectionString");
var dbContext = new DbContext(connectionString);
services.AddSingleton<IDbContext>(dbContext);
services.AddScoped(typeof(Repository<>), typeof(Repository<>));
// utilities
services.AddSingleton(new HttpClient());
services.AddSingleton(new Logger(dbContext));
// bll services
services.AddSingleton(
new LocationService(
new HttpClient(),
new Logger(dbContext),
new Repository<Country>(dbContext),
new Repository<Location>(dbContext)
)
);
}
Upvotes: 1
Views: 248
Reputation: 172646
I was expecting that having already registered those 4 dependencies as services, this would sort of take care of itself.
It will take care of itself. You just have to make use of the container's Auto-Wiring abilities:
services.AddScoped<LocationService>();
Do note that, to prevent Captive Dependencies, you should make sure that components do not depend on other components with a shorter lifestyle. For instance, do not let a Singleton
component depend on a Scoped
component. For that reason, LocationService
should not be registered as Singleton
, but rather as Scoped
or Transient
.
Upvotes: 1