我使用Microsoft的Unity进行依赖注入,我想做这样的事情:
IDataContext context = _unityContainer.Resolve<IDataContext>();
var repositoryA = _unityContainer.Resolve<IRepositoryA>(context); //Same instance of context
var repositoryB = _unityContainer.Resolve<IRepositoryB>(context); //Same instance of context
IDataContext context2 = _unityContainer.Resolve<IDataContext>(); //New instance
var repositoryA2 = _unityContainer.Resolve<IRepositoryA>(context2);
Run Code Online (Sandbox Code Playgroud)
RepositoryA并且RepositoryB都有一个带IDataContext参数的构造函数,我希望Unity使用我传递它的上下文初始化存储库.另请注意,IDataContext未在Unity中注册(我不想要3个实例IDataContext).
.net c# dependency-injection unity-container constructor-injection
我试图找出MEF的构造函数注入属性.我不知道如何告诉它加载构造函数的参数.
这是我正在尝试加载的属性
[ImportMany(typeof(BUsers))]
public IEnumerable<BUsers> LoadBUsers { get; set; }
Run Code Online (Sandbox Code Playgroud)
这是我用来导入程序集的代码.
try
{
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly()));
catalog.Catalogs.Add(new DirectoryCatalog("DI"));
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
Run Code Online (Sandbox Code Playgroud)
这是我正在尝试加载的类
[Serializable]
[Export(typeof(BUsers))]
public class EditProfile : BUsers
{
[ImportingConstructor]
public EditProfile(string Method, string Version)
{
Version = "2";
Action = "Edit";
TypeName = "EditProfile";
}
Run Code Online (Sandbox Code Playgroud) 我正在使用C#和Microsoft的Unity框架.我不太清楚如何解决这个问题.这可能与我对Unity缺乏理解DI有关.
我可以使用以下示例代码总结我的问题:
class Train(Person p) { ... }
class Bus(Person p) { ... }
class Person(string name) { ... }
Person dad = new Person("joe");
Person son = new Person("timmy");
Run Code Online (Sandbox Code Playgroud)
当我在Bus上调用resolve方法时,如何确保注入名为'timmy'的Person'onon'并在解析Train时如何确定具有当时名称'joe'的Person'add'得到解决?
我想也许可以使用命名实例?但我不知所措.任何帮助,将不胜感激.
顺便说一句,我宁愿不创建一个IPerson接口.
c# dependency-injection unity-container constructor-injection
我正在尝试使用Spring将SLF4J记录器注入类中,如下所示:
@Component
public class Example {
private final Logger logger;
@Autowired
public Example(final Logger logger) {
this.logger = logger;
}
}
Run Code Online (Sandbox Code Playgroud)
我找到了这个FactoryBean课程,我已经实现了.但问题是我无法获得有关注射目标的任何信息:
public class LoggingFactoryBean implements FactoryBean<Logger> {
@Override
public Class<?> getObjectType() {
return Logger.class;
}
@Override
public boolean isSingleton() {
return false;
}
@Override
public Logger getObject() throws Exception {
return LoggerFactory.getLogger(/* how do I get a hold of the target class (Example.class) here? */);
}
}
Run Code Online (Sandbox Code Playgroud)
FactoryBean甚至是正确的方法吗?当使用picocontainers 工厂注入时,你会得到Type传入的目标.在guice中它有点棘手.但是你如何在Spring中实现这一目标?
我有以下类,它使用构造函数注入:
public class Service : IService
{
public Service(IRepository repository, IProvider provider) { ... }
}
Run Code Online (Sandbox Code Playgroud)
对于这个类中的大多数方法,我只是为IRepository和创建Moq模拟IProvider和构造Service.但是,类中有一个方法可以在同一个类中调用其他几个方法.为了测试这个方法,我想测试该方法是否正确地调用这些方法并正确处理它们的返回值,而不是一起测试所有这些方法.
这样做的最好方法是嘲笑Service.我之前没有问题就用Moq模拟了具体的类.我甚至嘲笑了具有Moq构造函数参数的具体类,没有问题.但是,这是我第一次需要将模拟参数传递给模拟对象的构造函数.当然,我试着这样做:
var repository = new Mock<IRepository>();
var provider = new Mock<IProvider>();
var service = new Mock<Service>(repository.Object, provider.Object);
Run Code Online (Sandbox Code Playgroud)
但是,这不起作用.相反,我收到以下错误:
Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class: My.Namespace.Service.
Could not find a constructor that would match given arguments:
Castle.Proxies.IRepository
Castle.Proxies.IProvider
Run Code Online (Sandbox Code Playgroud)
如果Service构造函数接受像ints和strings 这样的简单参数,那么这种方法很好,但是如果它接受我正在嘲笑的接口则不行.你怎么做到这一点?
根据这篇文章,一个Controller应该有一个构造函数来获取要传入的接口,一个la:
public class DuckbillsController : ApiController
{
IDuckbillRepository _platypiRepository;
public DuckbillsController(IDuckbillRepository platypiRepository)
{
if (platypiRepository == null)
{
throw new ArgumentNullException("platypiRepository is null");
}
_platypiRepository = platypiRepository;
}
}
Run Code Online (Sandbox Code Playgroud)
但这个构造函数是如何调用的呢?通过客户端调用此类中包含的Web API方法,但是如何通过接口类型传递?或者这不一定发生(构造函数没有被任何人/从任何地方明确调用)?
规范示例在接口声明之前显示"private readonly",但是编译它不是必需的.是否有编译,我的意思是引人注目,有理由,让我先加上"私人只读"?
c# controller ioc-container constructor-injection asp.net-web-api
我正在试图弄清楚如何使用Simple Injector,我已经在项目周围使用它,没有注册简单服务及其组件的问题.
但是,我希望在具有两个以上实现接口的构造函数的组件时使用依赖注入器.
public DAL: IDAL
{
private Logger logger;
string _dbInstance;
public DAL()
{
logger = new Logger();
}
public DAL(string databaseInstance)
{
logger = new Logger();
_dbInstance = databaseInstance;
}
}
Run Code Online (Sandbox Code Playgroud)
以下是我注册服务的方式:
container.Register<IDAL, DAL>();
Run Code Online (Sandbox Code Playgroud)
运行代码,这是发生的错误:
要使容器能够创建DAL,它应该只包含一个公共构造函数,但它有2个.
删除构造函数后,下一个错误是它不允许我的构造函数接受参数.
DAL类型的构造函数包含String类型的参数'databaseInstance',它不能用于构造函数注入.
有什么方法我可以在类有2个以上的公共构造函数的情况下进行依赖注入吗?或者有一个接受参数的公共构造函数?
我在这里阅读文档:SimpleInjector(入门)
该文档开始易于理解,但它会呈指数级复杂,如果他们提到的后一个例子中的任何一个与我的问题有关,我就很难解读.
c# dependency-injection inversion-of-control constructor-injection simple-injector
如果我有一个ctor设置为多次注入的类,如下所示:
public Shogun(IEnumerable<IWeapon> allWeapons)
{
this.allWeapons = allWeapons;
}
Run Code Online (Sandbox Code Playgroud)
绑定设置如下:
Bind<IWeapon>().To<Sword>();
Bind<IWeapon>().To<Dagger>().WhenInjectedInto<Shogun>();
Run Code Online (Sandbox Code Playgroud)
然后我会期望将Shogun用两种武器注入?但事实并非如此 - 它只会得到匕首.
如果我添加这样的进一步绑定:
Bind<IWeapon>().To<Sword>();
Bind<IWeapon>().To<Dagger>().WhenInjectedInto<Shogun>();
Bind<IWeapon>().To<Shuriken>().WhenInjectedInto<Shogun>();
Run Code Online (Sandbox Code Playgroud)
然后Shogun得到了Dagger和Shuriken.WhenInjectedInto<T>()看起来它应该只限制它应用的绑定而不影响其他绑定.我发现这种行为非常误导.
有人能解释一下这里发生了什么吗?
c# dependency-injection ninject inversion-of-control constructor-injection
我遇到了Spring和构造函数注入的问题.我想用name(String)和特殊id(long)创建动态对象.
但是当加载spring.xml文件时会发生异常.
线程"main"java.lang.ExceptionInInitializerError中的异常
由以下原因引起:org.springframework.beans.factory.UnsatisfiedDependencyException:在类路径资源[spring.xml]中定义名称为'someBean'的bean时出错:通过构造函数参数表示的不满意的依赖关系,类型为[long]的索引0:不明确的构造函数参数types - 您是否将正确的bean引用指定为构造函数参数?
我的spring.xml:
<bean id="someBean" class="someClass" >
<constructor-arg index="0" type="java.lang.String" value=""/>
<constructor-arg index="1" type="long" value=""/>
</bean>
</beans>
Run Code Online (Sandbox Code Playgroud)
那有什么不对?构造函数arg的索引为1(而不是0,如例外)
我创建了2个简单的类.一个类的构造函数注释为@Autowired.它接受另一个类的对象.但是这段代码失败了.
类: - 1)SimpleBean.java
@Configuration
public class SimpleBean {
InnerBean prop1;
public InnerBean getProp1() {
return prop1;
}
public void setProp1( InnerBean prop1) {
System.out.println("inside setProp1 input inner's property is "
+ prop1.getSimpleProp1());
this.prop1 = prop1;
}
@Autowired(required=true)
public SimpleBean(InnerBean prop1) {
super();
System.out.println("inside SimpleBean constructor inner's property is "
+ prop1.getSimpleProp1());
this.prop1 = prop1;
}
}
Run Code Online (Sandbox Code Playgroud)
2)Inner.java
@Configuration
public class InnerBean {
String simpleProp1;
public String getSimpleProp1() {
return simpleProp1;
}
public void setSimpleProp1(String simpleProp1) {
this.simpleProp1 = simpleProp1; …Run Code Online (Sandbox Code Playgroud) spring annotations default-constructor constructor-injection