我有一个具有以下代码的BusinessLayer项目。域对象是FixedBankAccount(它实现了IBankAccount)。重构代码以避免反模式
存储库是作为域对象的公共属性,并作为接口成员。 如何重构它,使存储库不会成为接口成员?
域对象(FixedBankAccount)直接使用存储库来存储数据。这是否违反单一责任原则?如何纠正?
注意:存储库模式是使用LINQ to SQL实现的。
编辑
在下面的一个更好的方法给出的代码? https://codereview.stackexchange.com/questions/13148/is-it-good-code-to-satisfy-single-responsibility-principle
CODE
public interface IBankAccount
{
RepositoryLayer.IRepository<RepositoryLayer.BankAccount> AccountRepository { get; set; }
int BankAccountID { get; set; }
void FreezeAccount();
}
public class FixedBankAccount : IBankAccount
{
private RepositoryLayer.IRepository<RepositoryLayer.BankAccount> accountRepository;
public RepositoryLayer.IRepository<RepositoryLayer.BankAccount> AccountRepository
{
get
{
return accountRepository;
}
set
{
accountRepository = value;
}
}
public int BankAccountID { get; set; }
public void FreezeAccount()
{
ChangeAccountStatus();
}
private void SendEmail()
{
}
private void ChangeAccountStatus()
{
RepositoryLayer.BankAccount bankAccEntity = new RepositoryLayer.BankAccount();
bankAccEntity.BankAccountID = this.BankAccountID;
accountRepository.UpdateChangesByAttach(bankAccEntity);
bankAccEntity.Status = "Frozen";
accountRepository.SubmitChanges();
}
}
public class BankAccountService
{
RepositoryLayer.IRepository<RepositoryLayer.BankAccount> accountRepository;
ApplicationServiceForBank.IBankAccountFactory bankFactory;
public BankAccountService(RepositoryLayer.IRepository<RepositoryLayer.BankAccount> repo, IBankAccountFactory bankFact)
{
accountRepository = repo;
bankFactory = bankFact;
}
public void FreezeAllAccountsForUser(int userId)
{
IEnumerable<RepositoryLayer.BankAccount> accountsForUser = accountRepository.FindAll(p => p.BankUser.UserID == userId);
foreach (RepositoryLayer.BankAccount repositroyAccount in accountsForUser)
{
DomainObjectsForBank.IBankAccount acc = null;
acc = bankFactory.CreateAccount(repositroyAccount);
if (acc != null)
{
acc.BankAccountID = repositroyAccount.BankAccountID;
acc.accountRepository = this.accountRepository;
acc.FreezeAccount();
}
}
}
}
public interface IBankAccountFactory
{
DomainObjectsForBank.IBankAccount CreateAccount(RepositoryLayer.BankAccount repositroyAccount);
}
public class MySimpleBankAccountFactory : IBankAccountFactory
{
public DomainObjectsForBank.IBankAccount CreateAccount(RepositoryLayer.BankAccount repositroyAccount)
{
DomainObjectsForBank.IBankAccount acc = null;
if (String.Equals(repositroyAccount.AccountType, "Fixed"))
{
acc = new DomainObjectsForBank.FixedBankAccount();
}
if (String.Equals(repositroyAccount.AccountType, "Savings"))
{
acc = new DomainObjectsForBank.SavingsBankAccount();
}
return acc;
}
}
READING:
也许代码审查它是一个更好的地方? – gdoron
FWIW在大多数依赖注入场景中,必须在* class *上公开关于DI的工作方式(即在面值违反封装的情况下),然而,依赖项(如存储库)不需要添加到接口。对类实例的所有访问都将通过接口进行,因此Repository类属性为public的事实是非事件。但是,由于您正在使用工厂方法进行实例化,因此不需要公共依赖关系。 – StuartLC