服务类+实例化新类

时间:2011-11-07 17:18:37

标签: asp.net-mvc-2 c#-3.0 dns ninject

我想知道这是否是线程安全/良好做法。我的IOC是ninject,所有服务层调用都是通过默认设置(我认为在瞬态范围内?)。

问题,是否正确实例化new FileAllocation(loggedonuser,_repo)?最好的方法?做这个的最好方式是什么?这是一个域类,它包含可以从各种服务调用的逻辑,通常涉及一些数据库调用,大多数情况下不需要持久性...

无论如何,我通过一个界面调用我的服务方法,例如

void SaveFile(int reportid, stream file); //Interface name: IReportFileService


public Class FileService: Servicebase, IReportFileService
{

  private readonly IRepoSession _repo;
  public FileService(IUserSession user, IRepoSession repo, IUpdateSession update)
 : base(user,update)
 {
   _repo = repo;
 }

 //save file if users 'counter' is ok..
 public void SaveFile(int reportid, stream file)
 {

  //here I want to instantiate a new class that I store in my domain and store the counters
  //etc and do related db calls to check up relevant values

  //note loggedonuser is a prop on my *base class*
  var userChecks = new FileAllocation(loggedonuser,_repo);
  userChecks.CountEmUp(); //exception is thrown if 0, less than "limit" etc...

  base.update(userChecks.mycompany); //persist
  base.commit(); //base class method includes try, catch block...

 }

}

public class FileAllocation
{

 private readonly IRepoSession _repo;
 private readonly Loggedonuser _user;
 private int CompanyUploads;
 private int UserUploads;
 public Company mycompany;

 public FileAllocation(Loggedonuser user, IRepoSession repo)
 {
  _repo = repo;
  _user = user;
 }

 public void CountEmUp()
 {
   //do error checking,
   //load up other tables can user upload - permissions, count is ok etc...
   // check the upload type if of certain type we cannot proceed - call another method on this class

   //set myCompany variable to new limits etc...

 }

}

基本服务包含一个道具,我不想实例化来自其他服务,即更多一次,我该如何避免?

    private LoggedonuserDTO _currentuser = null;
    protected LoggedonuserDTO loggedonuser
    {
        get
        {
            if (_currentuser == null)
            {

                _currentuser = _user.GetCurrentUser(); //make db call here...
            }
            return _currentuser;
        }
    }

@Darin 建议:

public interface IFileAllocation
{
  CountEmUp(Loggedonuser currentuser);
}


//pass in loggedonuser to any method that requires it...
public class FileAllocation: IFileAllocation
{
  CountEmUp(Loggedonuser currentuser)
  { 
   //do whatever here...

  }
}

1 个答案:

答案 0 :(得分:1)

var userChecks = new FileAllocation(loggedonuser,_repo);

引入了FileServiceFileAllocation类之间的强耦合。如果这不是你的问题,那么你可以这样做。否则,您可以将此FileAllocation类的操作抽象为接口,然后将其注入FileService。这样FileServiceFileAllocation弱耦合,可以在不同的上下文中重用,单独测试单元。