Skip to content

Instantly share code, notes, and snippets.

@hanguksaram
Created September 21, 2017 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hanguksaram/69695558c6a7df35e1190c729dc94bfb to your computer and use it in GitHub Desktop.
Save hanguksaram/69695558c6a7df35e1190c729dc94bfb to your computer and use it in GitHub Desktop.
//Interface:
public interface IProjectService<T, K>: IService<T, K> where T: Project where K: ProjectRes{}
//Injected implementation:
public class ProjectService<T, K> : Service<T, K>, IProjectService<T, K> where T : Project where K : ProjectRes, new()
{
private readonly IRepo<T, K> repo;
private readonly IUnitOfWork uOfWork;
private readonly IMapper mapper;
public ProjectService(IProjectRepo<T, K> repo, IUnitOfWork uOfWork, IMapper mapper) : base(repo, uOfWork, mapper)
{
this.repo = repo;
this.uOfWork = uOfWork;
this.mapper = mapper;
}
public async override Task<IQueryable<K>> GetAll(){
var projects = this.repo.GetAll();
return projects.MapToProjectResource() as IQueryable<K>;
//var projecResourse =
}
}
//DI container in StartUp.cs:
//compiler allow me implement only such explicit declaration with real classes types in generic params
services.AddScoped(typeof(IProjectService<Project, ProjectRes>), typeof(ProjectService<Project, ProjectRes>));
// actually i curios if there is better solution than this one.
@ardalis
Copy link

ardalis commented Sep 21, 2017

This doesn't work?

    services.AddScoped(typeof(IProjectService<,>), typeof(ProjectService<,>));

If not, what is error?

@Tarig0
Copy link

Tarig0 commented Sep 28, 2017

I can confirm this works.

@Poltuu
Copy link

Poltuu commented Jul 24, 2018

I'm facing a similar issue where what I'd like to do would be something like this
services.AddScoped(typeof(IService<>), typeof(SpecificImplementationService<,TSpecificImplementation>));

So switching from open generic to semi open generic
Any idea how to do that ?

@M0ns1gn0r
Copy link

@Poltuu try creating a wrapper class for DI class OnlyForDI<T> : SpecificImplementationService<T,TSpecificImplementation>) and then register services.AddScoped(typeof(IService<>), typeof(OnlyForDI<>));.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment