我在" repository"中有一些接口和类。和"服务"并说如果我要使用FindBy方法,我会在IUserService中调用FindBy方法,这将最终在UserRepository中的FindBy方法中。接口和类看起来像这样:
public interface IUserService
{
User FindBy(string userName);
SimpleResult Insert(User user);
}
public class UserService : IUserService
{
private readonly IUserRepository userRepository;
public UserService(IUserRepository _userRepository)
{
userRepository = _userRepository;
}
public User FindBy(string userName)
{
return userRepository.FindBy(userName);
}
public SimpleResult Insert(User user)
{
return userRepository.Insert(user);
}
}
public interface IUserRepository
{
SimpleResult Delete(User user);
IList<User> FindAll();
User FindBy(long userID);
User FindBy(string userName);
SimpleResult Insert(User user);
SimpleResult Update(User user);
}
public class UserRepository : IUserRepository
{
Entities db = new Entities();
public User FindBy(long userID)
{
return db.Users.Where(x => x.UserID == userID).FirstOrDefault();
}
public SimpleResult Insert(User user)
{
SimpleResult result = new SimpleResult();
try
{
db.Users.Add(user);
db.SaveChanges();
result.SetSuccessStatus("Insert Success!");
}
catch (Exception ex)
{
result.SetErrorStatus(string.Format("Insert Failed! Cause : {0}", ex.Message));
}
return result;
}
//other methods
}
问题是,我只能通过在aspx.cs中实例化它来实现它:
public partial class Default : System.Web.UI.Page
{
IUserService userService = new UserService(new UserRepository());
}
IMO,它真是一团糟。我发现有人使用更简单的方法来实例化它:
public partial class Default : System.Web.UI.Page
{
IUserService userService { get; set; }
}
当我像这样实例化时,我得到一个null userService。我怎么能这样做?
答案 0 :(得分:1)
不确定您是否听说过依赖注入,它可能会有所帮助。可以使用很多不同的DI容器(Unity,Ninject,Autofac等)。有关DI和松散耦合的文章:http://joelabrahamsson.com/inversion-of-control-an-introduction-with-examples-in-net/
答案 1 :(得分:1)
你应该注入你对控制器构造函数的依赖
IPostRepository _repository;
public PostsController(IPostRepository repository)
{
_repository = repository;
}
你可以通过construnctor将你的依赖注入IOC容器(作为Ninject,你可以通过NUGet包下载)
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IPostRepository>().To<PostRepository>();
}
修改强>
网络表单版
从NinjectHttpApplication
继承全局(asax)并覆盖CreateKernel
方法
public class Global : NinjectHttpApplication
protected override IKernel CreateKernel()
{
IKernel kernel = new StandardKernel(new YourModule());
return kernel;
}
public class YourModule: Ninject.Modules.NinjectModule
{
public override void Load()
{
Bind<IPostRepository>().To<PostRepository>();
}
}
从Ninject.Web.PageBase
public partial class Default : PageBase
{
[Inject]
public IPostRepository _postRepository { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
Post post = _postRepository.Get(int postId);
}
}