--- a/Setup.hs
+++ b/Setup.hs
@@ -1,2 +1,22 @@
+{-# LANGUAGE CPP #-}
+module Main (main) where
+
+#ifndef MIN_VERSION_cabal_doctest
+#define MIN_VERSION_cabal_doctest(x,y,z) 0
+#endif
+
+#if MIN_VERSION_cabal_doctest(1,0,0)
+
+import Distribution.Extra.Doctest ( defaultMainWithDoctests )
+
+main :: IO ()
+main = defaultMainWithDoctests "doctests"
+
+#else
+
 import Distribution.Simple
+
+main :: IO ()
 main = defaultMain
+
+#endif
--- a/examples/doctest.hs
+++ b/examples/doctest.hs
@@ -1,6 +1,31 @@
 import Test.DocTest
-main
-  = doctest
-      [ "src"
-      , "examples"
-      ]
+
+import GHC.IO.Encoding (setLocaleEncoding)
+import System.Directory (getCurrentDirectory, makeAbsolute)
+import System.FilePath.Posix ((</>))
+import System.IO (utf8)
+import Build_doctests (pkgs)
+ 
+main :: IO ()
+main = do
+    setLocaleEncoding utf8
+    pwd    <- getCurrentDirectory
+    prefix <- makeAbsolute pwd
+
+    let customFlags =
+            [ "-package-env=-"
+            , "-hide-all-packages"
+            , "-no-global-package-db"
+            , "-no-user-package-db"
+            , "-package-db=" ++ prefix </> "dist/package.conf.inplace"
+            , "-package-db=" ++ prefix </> "package.conf.d"
+            ]
+
+    let modules =
+            [ "src"
+            , "examples"
+            ]
+
+    let args = customFlags ++ pkgs ++ modules
+
+    doctest args
--- a/generic-lens.cabal
+++ b/generic-lens.cabal
@@ -13,7 +13,7 @@ license-file:         LICENSE
 author:               Csongor Kiss
 maintainer:           kiss.csongor.kiss@gmail.com
 category:             Generics, Records, Lens
-build-type:           Simple
+build-type:           Custom
 
 tested-with:
   GHC == 9.14.1
@@ -35,6 +35,12 @@ extra-source-files:   examples/StarWars.hs
 
 extra-doc-files:      ChangeLog.md
 
+custom-setup
+    setup-depends:
+        base
+      , Cabal
+      , cabal-doctest
+
 library
   exposed-modules:    Data.Generics.Wrapped
                     , Data.Generics.Product
@@ -117,4 +123,8 @@ test-suite doctests
   main-is:            doctest.hs
   build-depends:      base >= 4 && <5
                     , doctest
+                    , directory
+                    , filepath
+                    , base-compat
+                    , lens
   hs-source-dirs:     examples
