嗨我从书中得到了代码:
public class Container {
Map<String, Object> components;
public Container() {
components = new HashMap<String, Object>();
Properties properties = new Properties();
try {
properties.load(new FileInputStream("components.properties"));
for (Map.Entry entry : properties.entrySet()) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
processEntry(key, value);
}
} catch (Exception ex) {
throw new RuntimeException();
}
}
private void processEntry(String key, String value) throws Exception {
String parts[] = key.split("\\.");
if (parts.length == 1) {
Object component = Class.forName(value).newInstance();
components.put(parts[0], component);
} else …Run Code Online (Sandbox Code Playgroud) 我现在正试图绕过IoC,我就是那里的一部分.我在SO的另一篇文章中找到的一个例子是:
http://blog.vascooliveira.com/unity-tutorial-and-examples/
我不太了解的是:
ILogger myExampleInstance = myContainer.Resolve(loggerType);
Run Code Online (Sandbox Code Playgroud)
我不确定loggerType是什么,因为它没有在任何地方提到它.
我可以看到,在这种情况下,IoC允许我们创建一种编写日志的方法.我们不是在代码中实例化特定类型的记录器,而是使用IoC来创建ILogger接口,然后我们对其进行编码.这意味着我假设我们并不特别关心使用什么类型的Logger.如果我们不在乎,我很想知道为什么我们需要传递一个loggerType,或者我们如何知道loggerType是由于关注点的分离.
我是理解它的一半,但我只需要最后的推动!=)
有两个文件:一个给出界面如下:
IStudentInterface.cs
public interface IStudentService
{
IEnumerable<Student> GetStudents();
Student GetStudentById(int id);
void CreateStudent(Student student);
void UpdateStudent(Student student);
void DeleteStudent(int id);
void SaveStudent();
}
Run Code Online (Sandbox Code Playgroud)
学生服务.cs:
public class StudentService : IStudentService
{
private readonly IStudentRepository _studentRepository;
private readonly IUnitOfWork _unitOfWork;
public StudentService(IStudentRepository studentRepository, IUnitOfWork unitOfWork)
{
this._studentRepository = studentRepository;
this._unitOfWork = unitOfWork;
}
#region IStudentService Members
public IEnumerable<Student> GetStudents()
{
var students = _studentRepository.GetAll();
return students;
}
public Student GetStudentById(int id)
{
var student = _studentRepository.GetById(id);
return student;
}
public void CreateStudent(Student …Run Code Online (Sandbox Code Playgroud) 我有以下课程:
public class MyClass {
@Inject
private MyAnotherClass myAnotherClass;
public MyClass() {
//Perform operations on myAnotherClass.
}
}
Run Code Online (Sandbox Code Playgroud)
我需要在构造函数中做一些需要实例的东西myAnotherClass.不幸的myAnotherClass是,在构造函数中的代码运行后注入,这意味着我正在执行操作null...
我当然可以MyAnotherClass myAnotherClass = new MyAnotherClass()直接在构造函数中将它实例化为经典的方式(),但我不认为在这种情况下做正确的事情.
你会建议什么解决方案来解决这个问题?
我正在使用Spring,当我使用new运算符创建实例时,我将注入的实例作为null,我可以调整场景.
例如,让A类和B类注入Main类
class Main
{
@autowired
A a;
@autowired
B b;
//getter and setter
}
class MainExecute
{
public static void main()
{
// loading the spring config xml
Main main = new Main();
A a=main.getA();
// whether a will get the instance ( I'm getting a as null)
}
Run Code Online (Sandbox Code Playgroud)
这种情况可能是什么原因请指导我
提前致谢.
我已经试过几乎所有的东西,但我不能让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
我们有一些遗留应用程序假设我们无法更改该 SiteSettings 类,因为完整的项目编码数千行会干扰。所以我们想用 DI 解决问题。我在这里创建了 POC 应用程序,您可以在global asax评论中 看到//HOW CAN I PASS TenantId HERE so it will be same for this complete httprequest life.
遗留代码:
public class OrderController
{
public static string CompleteOrder()
{
return SiteSettings.Instance.DefaultTimeZone();
}
}
public class SiteSettings
{
public ITenantSettings TenantSettings { get; set; }
private static SiteSettings _instance;
private SiteSettings() { }
public static SiteSettings Instance => _instance ?? (_instance = new SiteSettings());
public string DefaultTimeZone()
{
return TenantSettings.DefaultTimeZone();
}
}
Run Code Online (Sandbox Code Playgroud)
新的注射类 …
什么是bean生命周期?为什么控制反转不会自动调用destroy()方法,为什么我们要显式调用?
对于使用 Spring/Kotlin 注入 bean,我知道两种方法:将其传递到构造函数中:
@Service
open class MyService @Autowired constructor(
@Autowired
val myRepository: MyRepository
)
Run Code Online (Sandbox Code Playgroud)
使用“lateinit”关键字:
@Service
open class MyService {
@Autowired
lateinit var myRepository: MyRepository
}
Run Code Online (Sandbox Code Playgroud)
我知道这两部作品,但我想知道哪一部最好?是否存在我可以使用一种解决方案而不是另一种解决方案遇到的问题?
谢谢 !
我有一个Asp.net Core 3.1使用Kestrel服务器的遗留应用程序,我们所有的GET和POST调用都可以正常工作。我们的遗留应用程序上已经有一堆中间件,我们根据端点的不同将每个中间件用于不同的目的。
这就是我们的旧应用程序的设置方式,如下所示。我试图通过只保留重要的事情来使事情变得简单。
下面是我们的BaseMiddleware类,它由我们拥有的一堆其他中间件扩展。大约我们有 10 多个中间件扩展BaseMiddleware类 -
基础中间件.cs
public abstract class BaseMiddleware {
protected static ICatalogService catalogService;
protected static ICustomerService customerService;
private static IDictionary <string, Object> requiredServices;
private readonly RequestDelegate _next;
public abstract bool IsCorrectEndpoint(HttpContext context);
public abstract string GetEndpoint(HttpContext context);
public abstract Task HandleRequest(HttpContext context);
public BaseMiddleware(RequestDelegate next) {
var builder = new StringBuilder("");
var isMissingService = false;
foreach(var service in requiredServices) {
if (service.Value == …Run Code Online (Sandbox Code Playgroud) 我有一个简单的PHP MVC框架,它以这种方式工作:
StaticFramework (1)
|
V
DIC (2)
|
V
HTTPRequest
|
V
App <-> Router
|
V
Controller <-> Model
|
V
View
|
V
HTTPResponse
Run Code Online (Sandbox Code Playgroud)
(1) StaticFramework是一个静态的"前端控制器",它给出了App它的默认依赖性(2) DIC(依赖注入容器),它的工作方式与Pimple类似.可以访问容器以更改这些默认依赖项.例如,Router类被注入App了DIC.
我有一个问题,因为它是一个MVC应用程序,我有3个重要的层:
注入View很容易,因为它只是一个有一个render呈现PHP或HTML文件的方法的类,所以我只需要View在我的注入一个实例Controller.
但注入Model的Controller似乎更难.每个Model都是一个单独的类,所以我不能像我那样注入它View.每个人Model也可能需要其他依赖,例如a Database或XML类.
此外,我无法预测Controller将需要哪些型号,因为它可能需要其中的几种,例如,ArticleController需要ArticleModel和UsersModel. …
php model-view-controller dependencies dependency-injection inversion-of-control
我读到,每当我们在 spring 中执行 getBean() 时,它都会返回所需的对象。那么这是否意味着,如果我调用 getBean() 1000 次,就会创建 1000 个对象?如果是,那么 Spring 如何管理这些对象?如果否,请解释一下 Spring 如何在对象创建方面工作?有对象池之类的概念吗?请澄清我的疑问。我对 spring 很陌生,很困惑创建 spring 框架是为了让我们的任务变得简单还是让事情变得更复杂。Spring 似乎是一个 XML 网络 :(
c# ×4
spring ×4
java ×3
asp.net-core ×1
autofac ×1
automapper ×1
dependencies ×1
kotlin ×1
object ×1
php ×1
tapestry ×1
webforms ×1