{"id":36212916,"url":"https://github.com/uproid/instancer","last_synced_at":"2026-01-15T03:43:58.928Z","repository":{"id":332417051,"uuid":"1110884475","full_name":"uproid/instancer","owner":"uproid","description":"A simple, lightweight factory registry for Dart that makes creating instances of registered types easy and flexible.","archived":false,"fork":false,"pushed_at":"2025-12-05T22:23:56.000Z","size":21,"stargazers_count":4,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-01-13T20:44:15.311Z","etag":null,"topics":["dart","finch","flutter","instance","pub"],"latest_commit_sha":null,"homepage":"https://pub.dev/packages/instancer","language":"Dart","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/uproid.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null},"funding":{"github":"uproid","patreon":null,"open_collective":null,"ko_fi":"uproid","tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"lfx_crowdfunding":null,"polar":null,"buy_me_a_coffee":"fardziao","thanks_dev":null,"custom":null}},"created_at":"2025-12-05T21:52:19.000Z","updated_at":"2025-12-06T10:38:52.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/uproid/instancer","commit_stats":null,"previous_names":["uproid/instancer"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/uproid/instancer","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/uproid%2Finstancer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/uproid%2Finstancer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/uproid%2Finstancer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/uproid%2Finstancer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/uproid","download_url":"https://codeload.github.com/uproid/instancer/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/uproid%2Finstancer/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28412779,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-14T05:26:33.345Z","status":"ssl_error","status_checked_at":"2026-01-14T05:21:57.251Z","response_time":107,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dart","finch","flutter","instance","pub"],"created_at":"2026-01-11T04:05:05.276Z","updated_at":"2026-01-15T03:43:58.922Z","avatar_url":"https://github.com/uproid.png","language":"Dart","funding_links":["https://github.com/sponsors/uproid","https://ko-fi.com/uproid","https://buymeacoffee.com/fardziao","https://buymeacoffee.com/uproid"],"categories":[],"sub_categories":[],"readme":"# Instancer\n\n[![pub package](https://img.shields.io/pub/v/instancer.svg)](https://pub.dev/packages/instancer)\n[![Donate](https://img.shields.io/badge/Donate-Support-green.svg)](https://buymeacoffee.com/uproid)\n[![issues-closed](https://img.shields.io/github/issues-closed/uproid/instancer?color=green)](https://github.com/uproid/instancer/issues?q=is%3Aissue+is%3Aclosed) \n[![issues-open](https://img.shields.io/github/issues-raw/uproid/instancer)](https://github.com/uproid/instancer/issues) \n[![Contributions](https://img.shields.io/github/contributors/uproid/instancer)](https://github.com/uproid/instancer/blob/main/CONTRIBUTING.md)\n\nA simple, lightweight factory registry for Dart that makes creating instances of registered types easy and flexible.\n\nPerfect for dependency injection, prototyping, configuration management, and testing!\n\n## Features\n\n✨ **Simple API**: Just 5 intuitive methods to learn  \n🎯 **Type-safe**: Full generic type support  \n🪶 **Lightweight**: Zero dependencies  \n🔧 **Flexible**: Register any factory function  \n🧪 **Testable**: Easy to clear and reset for testing  \n\n## Getting started\n\nAdd this to your `pubspec.yaml`:\n\n```yaml\ndependencies:\n  instancer: ^1.0.0\n```\n\nThen import it:\n\n```dart\nimport 'package:instancer/instancer.dart';\n```\n\n## Usage\n\n### 🚀 Quick Start\n\n```dart\nimport 'package:instancer/instancer.dart';\n\nclass User {\n  final String name;\n  final int age;\n  \n  User({required this.name, required this.age});\n}\n\nvoid main() {\n  // 1️⃣ Register a factory function\n  Instancer.register\u003cUser\u003e(() =\u003e User(name: 'Guest', age: 18));\n  \n  // 2️⃣ Create instances anywhere in your code\n  final user1 = Instancer.create\u003cUser\u003e();\n  final user2 = Instancer.create\u003cUser\u003e();\n  \n  print(user1.name); // Output: Guest\n  print(identical(user1, user2)); // Output: false (different instances)\n}\n```\n\n### 📦 Real-World Examples\n\n#### Example 1: Configuration Management\n\n```dart\nclass AppConfig {\n  final String apiUrl;\n  final bool debugMode;\n  final int timeout;\n  \n  AppConfig({\n    required this.apiUrl, \n    required this.debugMode,\n    required this.timeout,\n  });\n}\n\nvoid main() {\n  // Development environment\n  Instancer.register\u003cAppConfig\u003e(\n    () =\u003e AppConfig(\n      apiUrl: 'http://localhost:3000',\n      debugMode: true,\n      timeout: 30,\n    ),\n  );\n  \n  // Use it anywhere in your app\n  final config = Instancer.create\u003cAppConfig\u003e();\n  print(config.apiUrl); // http://localhost:3000\n  \n  // Switch to production (just re-register)\n  Instancer.register\u003cAppConfig\u003e(\n    () =\u003e AppConfig(\n      apiUrl: 'https://api.production.com',\n      debugMode: false,\n      timeout: 10,\n    ),\n  );\n  \n  final prodConfig = Instancer.create\u003cAppConfig\u003e();\n  print(prodConfig.apiUrl); // https://api.production.com\n}\n```\n\n#### Example 2: Dependency Injection\n\n```dart\nclass Database {\n  void query(String sql) =\u003e print('Executing: $sql');\n}\n\nclass UserRepository {\n  final Database database;\n  \n  UserRepository({required this.database});\n  \n  void save(String name) {\n    database.query(\"INSERT INTO users (name) VALUES ('$name')\");\n  }\n}\n\nclass UserService {\n  final UserRepository repository;\n  \n  UserService({required this.repository});\n  \n  void createUser(String name) {\n    print('Creating user: $name');\n    repository.save(name);\n  }\n}\n\nvoid main() {\n  // Register dependencies in order\n  Instancer.register\u003cDatabase\u003e(() =\u003e Database());\n  \n  Instancer.register\u003cUserRepository\u003e(\n    () =\u003e UserRepository(database: Instancer.create\u003cDatabase\u003e()),\n  );\n  \n  Instancer.register\u003cUserService\u003e(\n    () =\u003e UserService(repository: Instancer.create\u003cUserRepository\u003e()),\n  );\n  \n  // Use the service\n  final userService = Instancer.create\u003cUserService\u003e();\n  userService.createUser('Alice');\n  // Output:\n  // Creating user: Alice\n  // Executing: INSERT INTO users (name) VALUES ('Alice')\n}\n```\n\n#### Example 3: Testing with Mocks\n\n```dart\nabstract class ApiClient {\n  Future\u003cString\u003e fetchData();\n}\n\nclass RealApiClient implements ApiClient {\n  @override\n  Future\u003cString\u003e fetchData() async {\n    // Real network call\n    return 'Real data from server';\n  }\n}\n\nclass MockApiClient implements ApiClient {\n  @override\n  Future\u003cString\u003e fetchData() async {\n    // Mock data for testing\n    return 'Mock data';\n  }\n}\n\nvoid main() {\n  // Production code\n  Instancer.register\u003cApiClient\u003e(() =\u003e RealApiClient());\n  \n  // In your tests, just re-register with mock\n  Instancer.register\u003cApiClient\u003e(() =\u003e MockApiClient());\n  \n  final client = Instancer.create\u003cApiClient\u003e();\n  client.fetchData().then(print); // Output: Mock data\n  \n  // Clean up after tests\n  Instancer.clear();\n}\n```\n\n#### Example 4: Prototype Pattern\n\n```dart\nclass EmailTemplate {\n  final String subject;\n  final String body;\n  final List\u003cString\u003e recipients;\n  \n  EmailTemplate({\n    required this.subject,\n    required this.body,\n    this.recipients = const [],\n  });\n  \n  @override\n  String toString() =\u003e 'Email: $subject to ${recipients.length} recipients';\n}\n\nvoid main() {\n  // Register a prototype template\n  Instancer.register\u003cEmailTemplate\u003e(\n    () =\u003e EmailTemplate(\n      subject: 'Welcome!',\n      body: 'Welcome to our service',\n      recipients: ['user@example.com'],\n    ),\n  );\n  \n  // Create multiple emails from the same template\n  final email1 = Instancer.create\u003cEmailTemplate\u003e();\n  final email2 = Instancer.create\u003cEmailTemplate\u003e();\n  \n  print(email1); // Email: Welcome! to 1 recipients\n  print(email2); // Email: Welcome! to 1 recipients\n  print('Same instance? ${identical(email1, email2)}'); // false\n}\n```\n\n#### Example 5: Factory with State\n\n```dart\nclass Logger {\n  static int _instanceCount = 0;\n  final int id;\n  \n  Logger() : id = ++_instanceCount;\n  \n  void log(String message) {\n    print('[Logger $id] $message');\n  }\n}\n\nvoid main() {\n  // Each creation increases the counter\n  Instancer.register\u003cLogger\u003e(() =\u003e Logger());\n  \n  final logger1 = Instancer.create\u003cLogger\u003e();\n  final logger2 = Instancer.create\u003cLogger\u003e();\n  final logger3 = Instancer.create\u003cLogger\u003e();\n  \n  logger1.log('First message');   // [Logger 1] First message\n  logger2.log('Second message');  // [Logger 2] Second message\n  logger3.log('Third message');   // [Logger 3] Third message\n}\n```\n\n## API Reference\n\n### `register\u003cT\u003e(T Function() factory)`\n\nRegisters a factory function for type `T`.\n\n```dart\nInstancer.register\u003cUser\u003e(() =\u003e User(name: 'John', age: 25));\n```\n\n**Parameters:**\n- `factory`: A function that returns a new instance of type `T`\n\n### `create\u003cT\u003e()`\n\nCreates a new instance of type `T` using the registered factory.\n\n```dart\nfinal user = Instancer.create\u003cUser\u003e();\n```\n\n**Returns:** A new instance of type `T`\n\n**Throws:** `StateError` if no factory is registered for type `T`\n\n### `isRegistered\u003cT\u003e()`\n\nChecks if a factory is registered for type `T`.\n\n```dart\nif (Instancer.isRegistered\u003cUser\u003e()) {\n  print('User factory is registered!');\n}\n```\n\n**Returns:** `true` if registered, `false` otherwise\n\n### `unregister\u003cT\u003e()`\n\nRemoves the factory for type `T`.\n\n```dart\nfinal removed = Instancer.unregister\u003cUser\u003e();\nprint('Factory removed: $removed');\n```\n\n**Returns:** `true` if a factory was removed, `false` if none existed\n\n### `clear()`\n\nRemoves all registered factories. Useful for testing or resetting state.\n\n```dart\nInstancer.clear();\n```\n\n### `count`\n\nReturns the number of registered factories.\n\n```dart\nprint('Total registered factories: ${Instancer.count}');\n```\n\n## Why Instancer?\n\n| Feature | Instancer | Traditional Singleton | Factory Pattern |\n|---------|-----------|----------------------|-----------------|\n| No inheritance required | ✅ | ❌ | ✅ |\n| No code generation | ✅ | ✅ | ✅ |\n| Multiple instances | ✅ | ❌ | ✅ |\n| Easy to test | ✅ | ❌ | ✅ |\n| Dynamic registration | ✅ | ❌ | ❌ |\n| Zero dependencies | ✅ | ✅ | ✅ |\n\n### Benefits:\n\n- **No inheritance required**: Your classes don't need to extend anything\n- **No code generation**: Works without `build_runner` or code generation\n- **Pure Dart**: No platform-specific code, works everywhere (Flutter, CLI, Web)\n- **Flexible**: Register simple constructors or complex initialization logic\n- **Testable**: Easy to swap implementations for mocking in tests\n- **Simple**: Only 5 methods to learn - `register`, `create`, `isRegistered`, `unregister`, `clear`\n\n## Common Use Cases\n\n✅ **Dependency Injection** - Register and inject dependencies  \n✅ **Configuration Management** - Switch between dev/prod configs  \n✅ **Testing** - Replace real implementations with mocks  \n✅ **Prototype Pattern** - Create multiple instances from templates  \n✅ **Factory Pattern** - Centralized instance creation  \n✅ **Plugin Systems** - Register and create plugin instances  \n\n## Tips \u0026 Best Practices\n\n### 1. Register early, use anywhere\n\n```dart\n// In your app initialization\nvoid setupDependencies() {\n  Instancer.register\u003cDatabase\u003e(() =\u003e SqliteDatabase());\n  Instancer.register\u003cApiClient\u003e(() =\u003e HttpApiClient());\n  Instancer.register\u003cAuthService\u003e(() =\u003e AuthService());\n}\n\n// Use anywhere in your app\nfinal auth = Instancer.create\u003cAuthService\u003e();\n```\n\n### 2. Use for environment-specific configurations\n\n```dart\nvoid setupConfig(Environment env) {\n  if (env == Environment.dev) {\n    Instancer.register\u003cConfig\u003e(() =\u003e DevConfig());\n  } else {\n    Instancer.register\u003cConfig\u003e(() =\u003e ProdConfig());\n  }\n}\n```\n\n### 3. Clean up in tests\n\n```dart\nvoid main() {\n  setUp(() {\n    Instancer.register\u003cService\u003e(() =\u003e MockService());\n  });\n  \n  tearDown(() {\n    Instancer.clear(); // Always clean up!\n  });\n  \n  test('service works', () {\n    final service = Instancer.create\u003cService\u003e();\n    // Test...\n  });\n}\n```\n\n## Contributing\n\nContributions are welcome! Please read our [CONTRIBUTING.md](CONTRIBUTING.md) for details.\n\n1. Check existing [issues](https://github.com/uproid/instancer/issues)\n2. Create a new issue or submit a pull request\n3. Follow the existing code style\n\n## License\n\nMIT License - see the [LICENSE](LICENSE) file for details.\n\n## Author\n\nCreated with ❤️ by [Uproid](https://github.com/uproid)\n\n---\n\n**Like this package?** Give it a ⭐ on [GitHub](https://github.com/uproid/instancer)!\n\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fuproid%2Finstancer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fuproid%2Finstancer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fuproid%2Finstancer/lists"}