简体   繁体   English

使用Unity注入DAAB数据库对象

[英]Inject DAAB Database Object with Unity

I'm trying to create a DAO object that takes a constructor dependency to the Data Access Application Block's Database object. 我正在尝试创建一个DAO对象,该对象将构造函数依赖项添加到数据访问应用程序块的Database对象。 How do I setup my .config file to have Unity resolve the dependency? 如何设置.config文件以使Unity解析依赖关系? I've tried mapping the Database type to create a Database object, but couldn't get it to work. 我尝试映射数据库类型以创建数据库对象,但无法使其正常工作。

Has anyone else tried doing anything like this? 有没有其他人尝试做这样的事情?

Just a starting hint, add a sample of the code you've done to your question. 只是一个开始提示,向问题中添加示例代码。 It tells us how far you've got, and at least what language you are using. 它告诉我们您已经走了多远,至少使用了什么语言。 I'll assume c#, EL V5 and starting from scratch: 我假设使用C#,EL V5,并从头开始:

Firstly let's review a standard constructor for a class that depends on the database application block: 首先,让我们回顾一下依赖于数据库应用程序块的类的标准构造函数:

private Microsoft.Practices.EnterpriseLibrary.Data.Database database;

public TestSQLConnection(Microsoft.Practices.EnterpriseLibrary.Data.Database injectedDatabase)
{
    database = injectedDatabase;
}

and here's how to call the creator: 以及如何调用创建者:

TestSQLConnection testSQLConnection =
    Microsoft.Practices.EnterpriseLibrary.Common.Configuration.EnterpriseLibraryContainer.Current.GetInstance<TestSQLConnection>(); 

So in short there's dependency injection for you, forget about how to create it, just ask for an instance of it and the library does the rest. 简而言之,就是为您提供了依赖注入,忘记了如何创建它,只要求它的一个实例,其余的工作由库完成。

The easiest way to create the config is to use the Enterprise Library V5 Configuration Tool, as it creates the necessary parts, I advise you to 'Read The Fine Manual'. 创建配置的最简单方法是使用企业库V5配置工具,因为它会创建必要的部分,因此建议您阅读“精读手册”。

If you are doing it manually here are the parts you need: 如果您手动进行操作,则需要以下部分:

<?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <!-- Tell EL what sections to use-->
        <configSections>
           <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
        </configSections>
        <!-- And use them -->
        <dataConfiguration defaultDatabase="MyDatabase" />
        <!-- This is just a plain connection string-->
        <connectionStrings>
            <add name="MyDatabase" connectionString="Data Source=DUMMY;Initial Catalog=default;Integrated Security=True" providerName="System.Data.SqlClient" />
        </connectionStrings>
    </configuration>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM