C# 在统一中解决依赖
我复制了一个使用AutoFac作为IOC的存储库模式示例,但在我的项目中,我使用UNITY,你知道如何在UNITY 3.0中编写这个吗 自动传真:C# 在统一中解决依赖,c#,dependency-injection,inversion-of-control,unity-container,C#,Dependency Injection,Inversion Of Control,Unity Container,我复制了一个使用AutoFac作为IOC的存储库模式示例,但在我的项目中,我使用UNITY,你知道如何在UNITY 3.0中编写这个吗 自动传真: builder.Register<IUserRepository>(x => new UserEntityRepository (x.Resolve<IDataContextFactory<SampleDataContext>>())).SingleInstance(); builder.Registe
builder.Register<IUserRepository>(x => new UserEntityRepository (x.Resolve<IDataContextFactory<SampleDataContext>>())).SingleInstance();
builder.Register(x=>newuserentityrepository(x.Resolve()).SingleInstance();
将注入IOC的类:
public class UserEntityRepository : EntityRepository<User, SampleDataContext>, IUserRepository
{
public UserEntityRepository(IDataContextFactory<SampleDataContext> databaseFactory)
: base(databaseFactory)
{ }
}
公共类UserEntityRepository:EntityRepository,IUserRepository
{
公共用户实体报告(IDataContextFactory数据库工厂)
:base(数据库工厂)
{ }
}
只需执行以下操作:
container.RegisterType<IUserRepository, UserEntityRepository>();
container.RegisterType();
如果注册了依赖项,Unity将自动解析构造函数参数。最简单的版本是
container.RegisterType<IUserRepository, UserEntityRepository>(
new ContainerControlledLifetimeManager() );
container.RegisterType(
新的ContainerControlled LifetimeManager());
但是,您所做的事情稍微复杂一些,因为它使您可以更自由地选择特定的参数值。在Unity中,您可以与注塑厂进行以下操作:
container.RegisterType<IUserRepository>(
new InjectionFactory(
c => new UserEntityRepository(
c.Resolve<IDataContextFactory<SampleDataContext>> ),
new ContainerControlledLifetimeManager() );
container.RegisterType(
新注射厂(
c=>newuserentityrepository(
c、 决心),
新的ContainerControlled LifetimeManager());
这看起来很像你的autofac版本。记得先注册数据上下文工厂。这一个按照我的预期工作…(基于Wiktor的解决方案)
container.RegisterType
(新的ContainerControlled LifetimeManager(),
new InjectionFactory(c=>new UserEntityRepository
(新的DefaultDataContextFactory());
您是基于配置的解决方案还是基于代码的解决方案?我正在寻找基于代码的Hanks Wiktor,injectionFactory提供了帮助。我在下面的回答中对代码做了一些调整。。
container.RegisterType<IUserRepository>
(new ContainerControlledLifetimeManager(),
new InjectionFactory(c => new UserEntityRepository
(new DefaultDataContextFactory<SampleDataContext>())));