Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AspNet Core Scoped Dependency Interface Segregation

So,

// this doesn't work or make sense
services.AddScoped<IReadSomething>(sp => new Something());
services.AddScoped<IWriteSomething>(sp => new Something());

So I have two Interfaces for the same Class, IReadSomething and IWriteSomething, the Class is just Something.

They need to be scoped because they transfer a subset of data from HttpContext to a arbitrary framework independent 'DTO'.

They both should be referencing the same Instance of Something, obviously one just exposes some read and the other, some write operations. So it gets written somewhere in the Middleware pipeline - and the rest of the app can just use the IReadSomething and read data so we can mitigate accidental data overwrite.

Doing,

services.AddScoped<IReadSomething, Something>();
services.AddScoped<IWriteSomething, Something>();

Doesn't make sense either because, quite rightly, it should create a new instance for each interface.

What am I missing to get Interface Segregation and Scoped Dependency Resolution to work together - I feel like I have to worry about the ASP.NET Core Scoped Service Factory or something?

I'm also using structuremap for my main dependency resolution - so an answer using that is fine.

like image 628
Callum Linington Avatar asked Dec 24 '22 04:12

Callum Linington


1 Answers

Make the target class scoped and then associate it with the desired interfaces

services.AddScoped<Something>();
services.AddScoped<IReadSomething>(sp => sp.GetService<Something>());
services.AddScoped<IWriteSomething>(sp => sp.GetService<Something>());

That way a call for either interface will return the same instance in scope

like image 141
Nkosi Avatar answered Jan 01 '23 12:01

Nkosi