在Unity中,Web.config等效于以下C#代码:
container
.RegisterType<IRepositoryProvider, RepositoryProvider>(
new PerRequestLifetimeManager(),
new InjectionConstructor(new object[] { new RepositoryFactories() })
);
我尝试了以下操作,但它不起作用:
<register type="Repository.Pattern.Ef6.Factories.IRepositoryProvider, Repository.Pattern.Ef6" mapTo="Repository.Pattern.Ef6.Factories.RepositoryProvider, Repository.Pattern.Ef6">
<lifetime type="Microsoft.Practices.Unity.PerRequestLifetimeManager, Microsoft.Practices.Unity.Mvc" />
<constructor>
<param name="repositoryFactories" value="new object[]{new RepositoryFactories()}"/>
</constructor>
</register>
困难的部分是如何处理&#34; new object [] {new RepositoryFactories()}&#34;。
答案 0 :(得分:0)
我认为您的配置不太合适。你需要依赖性attr。请参阅下面的示例。
Unity配置:
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<namespace name="ConsoleApplication8" />
<assembly name="ConsoleApplication8" />
<container name="MyContainer">
<types>
<type type="ConsoleApplication8.IRepositoryFactories, ConsoleApplication8"
mapTo="ConsoleApplication8.RepositoryFactories,
ConsoleApplication8" />
<type type="ConsoleApplication8.IRepositoryProvider, ConsoleApplication8"
mapTo="ConsoleApplication8.RepositoryProvider, ConsoleApplication8"
name="RepositoryProvider" >
<lifetime type="singleton" />
<constructor>
<param name="factories">
<dependency />
</param>
</constructor>
</type>
</types>
</container>
可能不需要完全限定名称作为程序集名称,并且命名空间已经注册。
<强>类型:强>
public interface IRepositoryProvider
{}
public class RepositoryProvider : IRepositoryProvider
{
private IRepositoryFactories _factories;
private string _name;
public RepositoryProvider(IRepositoryFactories factories) {
_factories = factories;
}
public RepositoryProvider(string name) {
_name = name;
}
}
public interface IRepositoryFactories { }
public class RepositoryFactories : IRepositoryFactories{}
class Program
{
static void Main(string[] args)
{
IUnityContainer container = new UnityContainer();
container.LoadConfiguration("MyContainer");
var instance = container.
Resolve<IRepositoryProvider>("RepositoryProvider");
}
}