在NodeJS中需要依赖注入

在NodeJS中需要依赖注入

本文介绍了在NodeJS中需要依赖注入,还是如何处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用nodej创建一些实验项目。我已经使用Spring编程了很多Java EE Web应用程序,并赞赏在那里轻松执行依赖注入。



现在我很好奇:如何使用节点进行依赖注入?还是:我甚至需要吗?是否有替代的概念,因为编程风格是不同的?



我正在谈论简单的事情,就像共享一个数据库连接对象,到目前为止,但我还没有找到一个满足我的解决方案。

解决方案

简而言之,你不需要像C#/ Java那样的依赖注入容器或服务定位器。由于Node.js利用模块模式,因此不需要执行构造函数或属性注入。虽然你仍然可以。



JS的好东西是,你可以修改任何东西来实现你想要的。



看到我非常跛脚的例子。



MyClass.js

  var fs = require('fs'); 

MyClass.prototype.errorFileExists = function(dir){
var dirsOrFiles = fs.readdirSync(dir);
(d dirOrFiles中的var d){
if(d ==='error.txt')return true;
}
返回false;
};

MyClass.test.js p>

  describe('MyClass',function(){
it('如果发现error.txt,应该返回错误目录',function(done){
var mc = new MyClass();
assert(mc.errorFileExists('/ tmp / mydir')); // true
});
});注意$ code> MyClass
取决于 fs 模块?正如@ShatyemShekhar所提到的,你可以像其他语言那样进行构造或属性注入。但是在Javascript中不是必需的。



在这种情况下,您可以做两件事。



fs.readdirSync 方法,或者您可以在调用 require 时返回完全不同的模块。



方法1:

  var oldmethod = fs.readdirSync; 
fs.readdirSync = function(dir){
return ['somefile.txt','error.txt','anotherfile.txt'];
};

*** PERFORM TEST ***
***测试后的RESTORE方法****
fs.readddirSync = oldmethod;

方法2:

  var oldrequire = require 
require = function(module){
if(module ==='fs'){
return {
readdirSync:function(dir){
return ['somefile.txt','error.txt','anotherfile.txt'];
};
};
} else
return oldrequire(module);

}

关键是利用Node.js的功能,的JavaScript。注意,我是一个CoffeeScript的人,所以我的JS语法可能在某个地方不正确。另外,我不是说这是最好的方式,但这是一种方式。



更新:



这应该解决您有关数据库连接的具体问题。我将创建一个单独的模块来封装数据库连接逻辑。如下所示:



MyDbConnection.js :(请务必选择更好的名字)

  var db = require('whichever_db_vendor_i_use'); 

module.exports.fetchConnection()= function(){
//逻辑来测试连接

//我想要连接池吗?

//在应用程序的整个生命周期中,我只需要一个连接吗?

return db.createConnection(port,host,databasename); //< ---通常来自配置文件的值
}

然后,任何需要数据库连接的模块将只包含您的 MyDbConnection 模块。



SuperCoolWebApp。 js

  var dbCon = require('./ lib / mydbconnection'); //文件存储在哪里

//现在用连接
var connection = dbCon.fetchConnection(); //mydbconnection.js负责池,重用,无论你的应用程序的用例是

//来到SuperCoolWebApp的TEST时间,你可以设置需要或返回任何你想要的,或者像我说的,使用与TEST数据库的实际连接。

不要逐字地按照这个例子。尝试通信您利用模块模式来管理您的依赖关系是一个跛脚的例子。希望这有一点帮助。


I currently creating some experimental projects with nodejs. I have programmed a lot Java EE web applications with Spring and appreciated the ease of dependency injection there.

Now I am curious: How do I do dependency injection with node? Or: Do I even need it? Is there a replacing concept, because the programming style is different?

I am talking about simple things, like sharing a database connection object, so far, but I have not found a solution that satisfies me.

解决方案

In short, you don't need a dependency injection container or service locater like you would in C#/Java. Since Node.js, leverages the module pattern, it's not necessary to perform constructor or property injection. Although you still can.

The great thing about JS is that you can modify just about anything to achieve what you want. This comes in handy when it comes to testing.

Behold my very lame contrived example.

MyClass.js:

var fs = require('fs');

MyClass.prototype.errorFileExists = function(dir) {
    var dirsOrFiles = fs.readdirSync(dir);
    for (var d in dirsOrFiles) {
        if (d === 'error.txt') return true;
    }
    return false;
};

MyClass.test.js:

describe('MyClass', function(){
    it('should return an error if error.txt is found in the directory', function(done){
        var mc = new MyClass();
        assert(mc.errorFileExists('/tmp/mydir')); //true
    });
});

Notice how MyClass depends upon the fs module? As @ShatyemShekhar mentioned, you can indeed do constructor or property injection as in other languages. But it's not necessary in Javascript.

In this case, you can do two things.

You can stub the fs.readdirSync method or you can return an entirely different module when you call require.

Method 1:

var oldmethod = fs.readdirSync;
fs.readdirSync = function(dir) {
    return ['somefile.txt', 'error.txt', 'anotherfile.txt'];
};

*** PERFORM TEST ***
*** RESTORE METHOD AFTER TEST ****
fs.readddirSync = oldmethod;

Method 2:

var oldrequire = require
require = function(module) {
    if (module === 'fs') {
        return {
            readdirSync: function(dir) {
                return ['somefile.txt', 'error.txt', 'anotherfile.txt'];
            };
        };
    } else
        return oldrequire(module);

}

The key is to leverage the power of Node.js and Javascript. Note, I'm a CoffeeScript guy, so my JS syntax might be incorrect somewhere. Also, I'm not saying that this is the best way, but it is a way. Javascript gurus might be able to chime in with other solutions.

Update:

This should address your specific question regarding database connections. I'd create a separate module for your to encapsulate your database connection logic. Something like this:

MyDbConnection.js: (be sure to choose a better name)

var db = require('whichever_db_vendor_i_use');

module.exports.fetchConnection() = function() {
    //logic to test connection

    //do I want to connection pool?

    //do I need only one connection throughout the lifecyle of my application?

    return db.createConnection(port, host, databasename); //<--- values typically from a config file
}

Then, any module that needs a database connection would then just include your MyDbConnection module.

SuperCoolWebApp.js:

var dbCon = require('./lib/mydbconnection'); //wherever the file is stored

//now do something with the connection
var connection = dbCon.fetchConnection(); //mydbconnection.js is responsible for pooling, reusing, whatever your app use case is

//come TEST time of SuperCoolWebApp, you can set the require or return whatever you want, or, like I said, use an actual connection to a TEST database.

Do not follow this example verbatim. It's a lame example at trying to communicate that you leverage the module pattern to manage your dependencies. Hopefully this helps a bit more.

这篇关于在NodeJS中需要依赖注入,还是如何处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 08:49