我正在尝试使用Simple Injector学习依赖注入,所以我创建了一个简单的程序.我查看了大量的例子,但没有找到类似的东西.Ninject有一个类似的例子,他们使用实现自我绑定实现
Bind<Samurai>().ToSelf();
Run Code Online (Sandbox Code Playgroud)
但我没有在简单的注射器中找到任何自我约束的例子.目前该程序运行良好,我得到了我正在寻找的预期结果,但这是正确的方法吗?该程序是最后一个代码示例.
接口
public interface ICar
{
void Move(string direction, int distance);
void Stop();
}
Run Code Online (Sandbox Code Playgroud)
类
public class Driver
{
private readonly ICar _car = null;
public Driver(ICar car)
{
this._car = car;
}
public void Drive(string direction, int distance)
{
_car.Move(direction, distance);
}
public void Brake()
{
_car.Stop();
}
}
Run Code Online (Sandbox Code Playgroud)
实现
public class Ferrari : ICar
{
public void Move(string direction, int distance)
{
Console.WriteLine("I am driving {0} really fast for {1} miles", direction, distance);
}
public …Run Code Online (Sandbox Code Playgroud) c# console-application constructor-injection simple-injector
我为一个简单的应用程序编写了某种控制台客户端.为了更灵活,我认为只依靠java.io.Input-/OutputStream而不是System.in/out直接访问会很好.
我将类重命名ConsoleClient为StreamClient,添加了setter并确保使用实例字段而不是System.in/out.
目前我的客户端代码如下所示:
ApplicationContext appCtx = new ClassPathXmlApplicationContext("...");
StreamClient cc = (StreamClient) appCtx.getBean("streamClient");
cc.setInputStream(System.in);
cc.setOutputStream(System.out);
cc.run(); // start client
Run Code Online (Sandbox Code Playgroud)
有没有办法将第3行和第4行移动到Spring配置中(最好是构造函数注入)?
谢谢你的时间.
我刚刚开始使用Ninject 2.0和ASP.NET MVC 2.因此,我有一个接口IMongoRepository和类MongoRepository.
MongoRepository接收参数字符串集合.
根据我想要使用的集合,我在MongoRepository的参数中传入一个不同的值.我希望我正确地说这个,但是我如何根据我使用的控制器映射不同的参数?
例如,在Article控制器中我会调用:
_articlesRepository = new MongoRepository("Articles");
Run Code Online (Sandbox Code Playgroud)
在PageController中我会调用:
_pagesController = new MongoRepository("Pages");
Run Code Online (Sandbox Code Playgroud)
我想做的只是做构造函数注入,然后传入IMongoRepository.任何想法或建议?
顺便说一句,我只是在学习IOC/DI; 所以,我愿意接受IOC忍者的任何提示!谢谢!
dependency-injection ninject constructor-injection ninject-2 asp.net-mvc-2
使用php ReflectionClass我可以找到我必须在类构造函数中注入哪些参数来创建新实例.
$class = new ReflectionClass($this->someClass);
$constructor = $class->getConstructor();
$parameters = $constructor->getParameters();
Run Code Online (Sandbox Code Playgroud)
是否还有一种方法可以获得这些参数的依赖关系.所以如果构造函数someClass看起来像这样:
public function __construct(Dependency $dependency){
$this->dependency = $dependency;
}
Run Code Online (Sandbox Code Playgroud)
我能以某种方式从构造函数中获取类Dependency吗?
php parameters constructor dependency-injection constructor-injection
我正在阅读Spring文档,我想知道它们的写作意味着什么:
Spring团队通常提倡构造函数注入,因为它使应用程序组件能够实现为不可变对象,并确保所需的依赖项不为空.
我没有看到它以什么方式实现组件为不可变的.虽然我知道使用基于构造函数的DI类似于使用final字段创建类的对象的自然Java方式,从而阻止对象更改字段引用.
这是他们使用这样一句话的唯一原因吗?有人可以向我解释一下吗?
谢谢.
java spring dependency-injection immutability constructor-injection
我正在处理一个项目并且一切正常,但是我有一个紧密耦合的依赖项,我不知道如何反转/注入。
问题出在我的 Consumer 类中,它将接收一条命令消息来启动一个进程,该进程是全局消息队列服务项目的一部分,例如MyCompany.MQ.Services,但对命令消息告诉它启动的进程具有紧密耦合的依赖关系,例如:
public Task Consume(ConsumeContext<MyMessageInterface> context)
{
logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
try
{
TightCoupleProcess tcp = new TightCoupleProcess(context);
logger.Information("{Blah}, {Blah}, {Blah}", context.Message.exampleVar1, context.Message.exampleVar2, context.Message.exampleVar3);
tcp.StartProcess();
return Task.CompletedTask;
}
catch (Exception ex)
{
return Task.FromException(ex);
}
}
Run Code Online (Sandbox Code Playgroud)
Task Consume是 MassTransit 的一部分,我无法修改 的签名,Consume因为这实际上IConsumer是MassTransit.
我想我想要的是一种反转/注入该依赖项的方法,以便我的全局MQ.services项目不依赖于调用它的项目。我想我对倒置/注入有一些误解,但我不确定如何表达我的缺点。也许我想要的不可能。我知道我不能修改接口实现,但如果像下面这样的东西工作,我会很酷,但由于Consume是 MassTransit 接口的实现,我认为我不能从我的调用类中注入匿名函数:
public Task Consume(ConsumeContext<MyMessageInterface> context, AnonFunc() func)
{
try
{
func(context)
logger.Information("{Blah}, {Blah}, {Blah}", context.Message.exampleVar1, context.Message.exampleVar2, context.Message.exampleVar3);
return Task.CompletedTask;
} …Run Code Online (Sandbox Code Playgroud) c# reflection dependency-injection masstransit constructor-injection
我可能会遗漏一些明显的东西......
但是当我学会欣赏IoC和ctor注入的荣耀时,我很难将它与对象图序列化协调起来.这两种模式是否兼容?为什么或者为什么不)?
假设有:
public class Foo
{
#region invariants
private readonly List<IBar> _bars;
private readonly Guid _id;
#endregion
public Foo( List<IBar> bars, Guid id )
{
_bars = bars.CannotBeNull("bars");
_id = id.CannotBeNull("id");
}
public List<IBar> Bars { get { return _bars; } }
//some other state I want serialized
}
public static class Ex
{
public static T CannotBeNull<T>( this T obj, string paramName = "" )
{
if ( null == obj ) throw new ArgumentNullException(paramName);
return obj;
} …Run Code Online (Sandbox Code Playgroud) architecture dependency-injection ninject inversion-of-control constructor-injection
我在使用带有构造函数属性的 DI 时遇到问题。我正在构建一个PDFBuilder基于我的IPDFBuilder.
public interface IPDFBuilder
{
string templatefilepath { get; }
string templatefilename { get; }
Dictionary<string, string> dict { get; }
void CreatePDF();
}
public class PDFBuilder : IPDFBuilder
{
public string templatefilename { get; private set; }
public string templatefilepath { get; private set; }
public Dictionary<string, string> dict { get; private set; }
public PDFBuilder(string templatefilename, string templatefilepath, Dictionary<string, string> dict)
{
this.templatefilename = templatefilename;
this.templatefilepath = templatefilepath;
this.dict = dict;
} …Run Code Online (Sandbox Code Playgroud) 我正在开发Java Spring应用程序。我的应用程序中有一些使用.yml配置文件配置的字段。我想在有关字段上使用@Value注释导入这些值。我还想使用构造函数注入的最佳实践,而不是使用字段注入,但是我想使用Lombok而不是手动编写我的构造函数。有什么办法可以一次完成所有这些事情?例如,这不起作用,但与我想要执行的操作类似:
@AllArgsConstructor
public class my service {
@Value("${my.config.value}")
private String myField;
private Object myDependency;
...
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我想要的是Lombok生成仅设置myDependency的构造函数,并使myField从配置文件中读取。
谢谢!
我正在努力理解StructureMap的部分用法.特别是,在文档中有一个关于常见反模式的声明,仅使用StructureMap作为服务定位器而不是构造函数注入(直接来自Structuremap文档的代码示例):
public ShippingScreenPresenter()
{
_service = ObjectFactory.GetInstance<IShippingService>();
_repository = ObjectFactory.GetInstance<IRepository>();
}
Run Code Online (Sandbox Code Playgroud)
代替:
public ShippingScreenPresenter(IShippingService service, IRepository repository)
{
_service = service;
_repository = repository;
}
Run Code Online (Sandbox Code Playgroud)
这对于一个非常短的对象图很好,但是当处理很多级别的对象时,这是否意味着你应该从顶部向下传递更深层对象所需的所有依赖项?当然,这会破坏封装并暴露有关更深层对象实现的过多信息.
假设我正在使用Active Record模式,因此我的记录需要访问数据存储库才能保存和加载自身.如果此记录加载到对象内,该对象是否调用ObjectFactory.CreateInstance()并将其传递给活动记录的构造函数?如果该对象在另一个对象内部怎么办?是否将IRepository作为自己的参数进一步向上?这将向父对象公开我们此时访问数据存储库的事实,外部对象可能不应该知道.
public class OuterClass
{
public OuterClass(IRepository repository)
{
// Why should I know that ThingThatNeedsRecord needs a repository?
// that smells like exposed implementation to me, especially since
// ThingThatNeedsRecord doesn't use the repo itself, but passes it
// to the record.
// Also where do I create repository? Have to instantiate …Run Code Online (Sandbox Code Playgroud) structuremap dependency-injection service-locator constructor-injection
我正在使用.NET Core构造函数注入。在一位同事的代码审查中,他提出了一个问题,即我是否应该检查控制器中注入的依赖项的空值。
由于该框架负责创建服务的实例,因此在我看来,它将处理所有错误,并且永远不会将空值依赖项传递给构造函数。不过,我没有任何事实证据,因此我想知道是否有必要进行null检查。
例如,是否应该检查以下代码中的“ myService”是否为null?(假设代码配置为使用DI)
public class MyController
{
private readonly IMyService _myService;
public MyController(IMyService myService)
{
_myService = myService;
}
}
Run Code Online (Sandbox Code Playgroud) c# dependency-injection constructor-injection null-check .net-core
我有两个班级。学生和 SMSSenderMessage。其中 Student 依赖于 SMSSenderMessage,而 SMSSenderMessage 依赖于 Student。Student 和 SMSSenderMessage 只有一个构造函数。我想对这两个类使用构造函数注入。
public interface IPerson
{
string GetName();
}
public interface ISenderMessage
{
void Send(string text);
}
public class Student : IPerson
{
private ISenderMessage S;
public string Name { get; set; }
public Student(ISenderMessage s)
{
this.S = s;
}
public void DoSomeThing()
{
//...Some Thing
S.Send("Hello");
}
public string GetName()
{
return this.Name;
}
}
public class SMSSenderMessage : ISenderMessage
{
IPerson P;
public SMSSenderMessage(IPerson p)
{
P = …Run Code Online (Sandbox Code Playgroud) c# constructor dependency-injection inversion-of-control constructor-injection
我已经试过几乎所有的东西,但我不能让AutoMapper映射A =>乙当B没有参数的构造函数.
我正在使用Unity并且所有依赖项都被方便地注册了,但是,我怎么说AutoMapper"嘿,如果目标实例需要构造函数中的某些依赖项,请让Unity构建它,然后再进行映射.
我试过了
Mapper.Initialize(configuration =>
{
configuration.ConstructServicesUsing(container.Resolve);
configuration.CreateMap<Person, PersonViewModel>();
});
Run Code Online (Sandbox Code Playgroud)
但它不起作用:(
编辑:事实上,我撒谎了一下.我没有使用Unity.我正在使用格雷斯,但不想提出一个相对未知的容器询问有关进展主题:)
我已经解决了这个问题,它和丝绸一样光滑.确切的代码是这样的.请记住,我正在使用Grace IoC Container(我热切推荐).
Bootstrapper.Instance.Configure(new CompositionRoot());
Mapper.Configuration.ConstructServicesUsing(type => Bootstrapper.Instance.Container.Locate(type));
Mapper.CreateMap<Person, PersonViewModel>()
.ConstructUsingServiceLocator();
Run Code Online (Sandbox Code Playgroud) inversion-of-control unity-container automapper constructor-injection
c# ×5
java ×3
spring ×3
constructor ×2
ninject ×2
.net-core ×1
architecture ×1
automapper ×1
immutability ×1
lombok ×1
masstransit ×1
ninject-2 ×1
null-check ×1
parameters ×1
php ×1
reflection ×1
structuremap ×1