我有这样定义的服务:
public class MentorService : IMentorService
{
private readonly Func<MentorContext> _dbFactory;
public MentorService(string connectionString)
{
this._dbFactory = () => new MentorContext(connectionString);
}
public MentorService()
{
this._dbFactory = () => new MentorContext();
}
public MentorContext CreateContext()
{
return _dbFactory.Invoke();
}
public IList<User> GetUsers()
{
using (var db = CreateContext())
{
return db.Users.ToList();
}
}
// etc etc
}
在我的 API 控制器中,我有以下内容:
public class UserController : ApiController
{
private readonly IMentorService _mentorService;
public UserController()
{
_mentorService = new MentorService();
}
public UserController(IMentorService mentorService)
{
_mentorService = mentorService;
}
}
我想将服务分解为子服务以便于维护和测试——比如 UserService、BookService 等。然后我只想在我的控制器中使用一个服务。
如何才能做到这一点?