c# - 使用构造函数依赖注入(inject)检索文件的简单工厂

标签 c# asp.net-mvc inversion-of-control factory

我想创建一个灵活的类,因此我可以切换实现。

问题:存储文件/文档
选项:在服务器文件系统、数据库等本地存储。

有人可以帮忙介绍一下类(class)的骨架结构吗?我怎么称呼它?

我没有使用 IoC,也不想使用。我只想要在工厂中进行 1 次代码更改以调用另一个实现的灵 active 。

最佳答案

使用接口(interface)。

interface IStorage
{
    void Save(string filename);
}

然后创建您的各种实现:
class LocalStorage : IStorage
{
    void Save(string filename)
    {
        -implementation code-
    }
}

然后,在你的消费类
IStorage storage = new LocalStorage();

// uses local storage
storage.Save();

storage = new DatabaseStorage();

// now use database storage
storage.Save();

关于c# - 使用构造函数依赖注入(inject)检索文件的简单工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1924129/

相关文章:

c# - 如何在Redis缓存中存储列表元素

c# - C# 5.0 中的捕获闭包(循环变量)

dependencies - 当依赖关系发生变化时,依赖反转主体 (DIP) 如何减少对依赖模块进行更改的需要?

asp.net-mvc - 为服务层设计 DI(构造函数注入(inject))存储库

c# - Jabber 作为 asp.net 网站的聊天系统

c# - 使用最小起订量模拟通用存储库

c# - ASP.NET Core FromBody 模型绑定(bind) : Bind a Class with Interafece Field

javascript - 从 mvc.net 获取 AngularJS http 中使用的 url 的可靠方法是什么?

ruby-on-rails - Couchapp 是 Web 框架的现实替代品吗?

inversion-of-control - 用于完整框架 (4.7) 和 IoC 的 IHttpClientFactory