简体   繁体   中英

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. How do I setup my .config file to have Unity resolve the dependency? 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:

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'.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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