在web窗体类中读取多个httpContext调用的干净方法



我想知道其他人是否可以选择将以下内容写为"干净代码">

此外。。。这是用VB写的,但我很乐意在C#中得到建议

(我只是在记事本上写了这个……可能不会编译,但这是我质疑的原则(

public class MyTest
public sub new()
end sub
public sub SaveSomething(message as string)
save($"{GetSessionId} == {GetIdentityName} == {message}")   
if configurationmanager.appsettings("allowSomething") then
doSomethingElse()
end if
end function
private function GetSessionId as string
if httpcontext.current?.session?.sessionID isNot Nothing then
return httpcontext.current.session.sessionID
else
return ""
end if
end function
private function GetIdentityName as string
if httpcontext.current?.user?.identity?.name isNot Nothing then
return httpcontext.current.user.identity.name
else
return ""
end if
end function
private sub save(message)
dim filePath as string = configurationmanager.appsettings("filePath")
'some code here to save
end sub
private sub doSomethingElse()
'some code here
end sub
end class

现在,我想去掉所有的"httpContext"one_answers"ConfigurationManager"引用(更干净,这样我就可以进行单元测试等…(

我考虑过的一种方法是为这四种情况创建提供者类,例如

_SessionIdProvider as ISessionIdProvider
_IdentityNameProvider as INameProvider
_FilePathProvider as IPathProvider
_AppSettingsAllowSomethingProvider as IAllowSomethingProvider

把这些都注入!我现在认为这是一个混乱的

我考虑了一个helper类,所以要注入一个对象,我可以用它来获得这些值。。但是解决方案中的其他地方可能需要sessionID,例如,其他值不在这个助手类中,因此可能有重复的代码,或者有一个巨大的助手类

有什么想法吗?像这样注入太多依赖项是不是很麻烦?

我不认为四个依赖项太多,但它可能处于边缘。。。我建议您遵循依赖反转原则,让客户端类(MyTest("设计"它需要的接口。

但是,由于所讨论的方法都不接受任何参数,因此可以将所有依赖关系减少为基元依赖关系。

在C#中,它可能看起来像这样:

public class MyTest
{
public MyTest(string sessionId, string identityName, bool allowSomething, string filePath)
{
SessionId = sessionId;
IdentityName = identityName;
AllowSomething = allowSomething;
FilePath = filePath;
}
public string SessionId { get; }
public string IdentityName { get; }
public bool AllowSomething { get; }
public string FilePath { get; }
public void SaveSomething(string message)
{
Save($"{SessionId} == {IdentityName} == {message}");
if (allowSomething))
DoSomethingElse();
}
private void Save(message)
{
var filePath = FilePath;
// some code here to save
}
private void DoSomethingElse()
{
// some code here
}
}

三个值SessionIdIdentityNameAllowSomething看起来像是属于一组与身份验证和授权相关的值,因此它们可能更适合作为参数对象。

最新更新