Files
vue-desktop/src/services/di/example.ts
2025-10-11 11:30:44 +08:00

95 lines
2.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 依赖注入系统使用示例
*/
// 1. 系统启动示例 - 通常在应用入口文件中使用
import { systemBootstrapper } from './SystemBootstrapper'
import { ServiceProvider, Inject } from './ServiceProvider'
import { ServiceIds } from './ServiceRegistry'
// 启动系统(通常在应用入口点调用一次)
async function startApplication() {
try {
console.log('正在启动应用...')
// 启动整个系统,包括初始化服务容器和所有服务
const success = await systemBootstrapper.bootstrap()
if (!success) {
throw new Error('系统启动失败')
}
console.log('应用启动成功!')
// 应用初始化完成后,可以开始使用各种服务
initializeApplication()
} catch (error) {
console.error('应用启动失败:', error)
}
}
// 应用初始化
function initializeApplication() {
// 2. 使用静态服务提供者访问服务
const windowService = ServiceProvider.getWindowFormService()
const resourceService = ServiceProvider.getResourceService()
console.log('访问服务示例:', {
windowServiceAvailable: !!windowService,
resourceServiceAvailable: !!resourceService
})
// 3. 创建并初始化一个使用依赖注入的组件
const appComponent = new ApplicationComponent()
appComponent.initialize()
}
// 4. 在组件中使用依赖注入
class ApplicationComponent {
// 使用装饰器自动注入服务
@Inject(ServiceIds.WINDOW_FORM_SERVICE)
private windowFormService: any
@Inject(ServiceIds.RESOURCE_SERVICE)
private resourceService: any
@Inject(ServiceIds.LIFECYCLE_MANAGER)
private lifecycleManager: any
initialize() {
console.log('组件初始化,服务已注入:', {
windowFormService: !!this.windowFormService,
resourceService: !!this.resourceService,
lifecycleManager: !!this.lifecycleManager
})
// 使用注入的服务
this.setupComponent()
}
private setupComponent() {
// 示例:使用窗口服务创建一个新窗口
// 注意这只是示例代码实际使用时需要根据具体服务API调整
console.log('组件正在使用注入的服务设置UI...')
}
}
// 5. 动态获取服务示例
function dynamicServiceExample(serviceId: string) {
// 使用get方法动态获取服务
try {
const service = ServiceProvider.getServiceById(serviceId as any)
console.log(`动态获取服务[${serviceId}]:`, !!service)
return service
} catch (error) {
console.error(`无法获取服务[${serviceId}]:`, error)
return null
}
}
// 导出示例函数供其他文件使用
export { startApplication, dynamicServiceExample, ApplicationComponent }
// 注意在实际应用中你会在main.ts或应用入口文件中调用startApplication()
// startApplication(); // 取消注释以启动应用