3

我正在尝试将一些C#MVC 遗留代码移动到共享 DLL 中。到目前为止一切顺利,但有人问我该共享 DLL 不需要System.Web以任何方式引用。

System.Web 的 DLL 中使用的唯一类型是HttpPostedFileBase

public string ChangeAttachment(int userId, HttpPostedFileBase file)
{
    string attachmentsFolderPath = ConfigurationManager.AppSettings["AttachmentsDirectory"];
    if (!Directory.Exists(attachmentsFolderPath))
    {
        Directory.CreateDirectory(attachmentsFolderPath);
    }

    string fileTarget = Path.Combine(attachmentsFolderPath, userId.ToString() + Path.GetExtension(file.FileName));

    if (File.Exists(fileTarget))
    {
        File.Delete(fileTarget);
    }

    file.SaveAs(fileTarget);

    return fileTarget;
}

如您所见,这里不需要 HTTP 或 Web 功能,因为只使用了它的FileNameSaveAs()成员。

是否有一个替代品可以在调用者HttpPostedFileBase处轻松转换为它,以便我需要作为参数传递的只是一个非 Web 文件?

注意:HttpPostedFileBase直接继承自System.Object,而不是任何文件类。

4

2 回答 2

4

HttpPostedFileBase是一个抽象类。所以挑战在于你实际上并没有替换那个类,你正在替换HttpPostedFileWrapper,这是实现。(这不是类继承自什么,而是从它继承什么。)

HttpPostedFileWrapper反过来引用其他System.Web类,如HttpInputStream和 'HttpPostedFile`。

所以你不能替换它。也许通过要求您不要引用 System.Web 的意图是您正在移动与 Web 功能不直接相关的遗留代码,例如业务逻辑。如果您不能完全不使用代码,也许您可​​以将其从您正在创建的新程序集中删除,然后再使用另一个程序集来引用System.Web. 如果他们不需要这个特定的功能,他们只引用一个程序集,但如果他们需要这个,那么他们还可以添加第二个引用的程序集System.Web

于 2016-03-27T17:17:47.627 回答
1

如果您不想引用System.Web并且还想使用SaveAs方法,则可以定义一个接口和一个包装器来建立链接。虽然这不是一个非常简单的方法:

//// Second assembly (Without referencing System.Web):
// An interface to link the assemblies without referencing to System.Web
public interface IAttachmentFile {
    void SaveAs(string FileName);
}
..
..
// Define ChangeAttachment method
public string ChangeAttachment(int userId, IAttachmentFile attachmentFile) { 
   string attachmentsFolderPath = ConfigurationManager.AppSettings["AttachmentsDirectory"];
   if (!Directory.Exists(attachmentsFolderPath)) {
        Directory.CreateDirectory(attachmentsFolderPath);
   }
   string fileTarget = Path.Combine(
        attachmentsFolderPath, 
        userId.ToString() + Path.GetExtension(file.FileName) 
   );
   if (File.Exists(fileTarget)) {
       File.Delete(fileTarget);
   }
   // This call leads to calling HttpPostedFileBase.SaveAs
   attachmentFile.SaveAs(fileTarget);
   return fileTarget;
}

//// First assembly (Referencing System.Web):
// A wrapper class around HttpPostedFileBase to implement IAttachmentFile   
class AttachmentFile : IAttachmentFile {
    private readonly HttpPostedFileBase httpPostedFile;
    public AttachmentFile(HttpPostedFileBase httpPostedFile) {
        if (httpPostedFile == null) {
            throw new ArgumentNullException("httpPostedFile");
        }
        this.httpPostedFile = httpPostedFile;
    }
    // Implement IAttachmentFile interface
    public SaveAs(string fileName) {
        this.httpPostedFile.SaveAs(fileName);
    }
}
..
..
// Create a wrapper around the HttpPostedFileBase object
var attachmentFile = new AttachmentFile(httpPostedFile);

// Call the ChangeAttachment method
userManagerObject.ChangeAttachment(userId, attachmentFile);
于 2016-03-27T20:39:39.123 回答