简体   繁体   中英

The type is defined in an assembly that is not referenced. c#, Generic Repository Pattern, URF

I'm using a generic repository. My service layer talks to my repository and maps entities to domain models with automapper. My controllers talk to my service layer and know nothing of entities or the repository.

I am trying to create a generic service class for all the basic CRUDs.

My generic service looks like this (cut down):

public interface IService<TModel, TEntity>
{
    void Add(TModel model)
}

public abstract class Service<TModel, TEntity> : IService<TModel, TEntity>
{
    private readonly IGenericRepository<TEntity> _repository;

    protected Service(IGenericRepository<TEntity> repository) { _repository = repository; }

    public virtual void Add(TModel model) { _repository.Add(AutoMapper.Mapper.Map<TEntity>(model)); }
}

My Student service:

public interface IStudentService : IService<Model.Student, Entity.Student>
{ }

public class StudentService : Service<Model.Student, Entity.Student>, IStudentService 
{
    private readonly IGenericRepository<Entity.Student> _repository;

    public StudentService (IGenericRepository<Entity.Student> repository) : base(repository)
    {
        _repository = repository;
    }
}

And my controller

public class StudentController
{
    private readonly IStudentService _studentService;

    public StudentController(IStudentService studentService)
    {
        _studentService = studentService;
    }

    public ActionResult AddStudent(Student model)
    {
        _studentService.Add(model); //ERROR
    }
}

I get the following when calling add from my controller (line marked with ERROR above).

The type is defined in an assembly that is not referenced. You must add a reference to MyProject.Entities

I understand the reason for the error but didn't think it would be a problem as my service accepts and returns models only and doesn't need to know about entities?

Is there another way to accomplish what I want so I can keep from referencing entities in my controller class?

For completeness, I should probably make this as an answer.

Just change the Service interface not to take the Entity Type Parameter:

public interface IService<TModel> {
    // ...
}

and keep the type parameter on the abstract class.

public abstract class Service<TModel, TEntity> : IService<TModel> {
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM